How do I slice lists in Python in pure Python?

In Python, slicing lists allows you to access a subset of elements within a list. You can specify a start index, an end index, and an optional step to retrieve elements from the original list.

Here are some common examples of list slicing:

# Sample list my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # Slicing from index 2 to index 5 (exclusive) print(my_list[2:5]) # Output: [2, 3, 4] # Slicing from the start to index 4 (exclusive) print(my_list[:4]) # Output: [0, 1, 2, 3] # Slicing from index 5 to the end print(my_list[5:]) # Output: [5, 6, 7, 8, 9] # Slicing with a step of 2 print(my_list[::2]) # Output: [0, 2, 4, 6, 8]

list slicing Python programming data manipulation access elements