Python list slicing is a technique that allows you to extract a subset of elements from a list by specifying a range of indices. The syntax for slicing is list[start:end:step]
, where:
start
: The index where the slice begins (inclusive).
end
: The index where the slice ends (exclusive).
step
(optional): The interval between each element in the slice.
Basic Slicing
list[start:end]
: Extracts elements starting from the index start
up to, but not including, the index end
.
Example:
numbers = [0, 1, 2, 3, 4, 5, 6, 7]
# Extract elements from index 2 to 5 (excluding index 5)
subset = numbers[2:5]
print(subset) # Output: [2, 3, 4]
Omitting start or end
Omitting start means the slice starts from the beginning.
my_list = [0, 1, 2, 3, 4, 5]
sliced = my_list[:3] # Returns [0, 1, 2]
Omitting end means the slice goes till the end of the list
my_list = [0, 1, 2, 3, 4, 5]
sliced = my_list[2:] # Returns [2, 3, 4, 5]
Using negative indices:
Negative indices start counting from the end of the list
my_list = [0, 1, 2, 3, 4, 5]
sliced = my_list[-3:] # Returns [3, 4, 5]
Using step:
the step parameter determines the number of indices to skip between each selected element.
A positive step value (e.g., 2
) skips that many indices forward.
Example: step=2
means every second element is taken.
my_list = [0, 1, 2, 3, 4, 5]
sliced = my_list[::2] # Returns [0, 2, 4]
Example: step=
3 means every third element is taken.
my_list = [0, 1, 2, 3, 4, 5]
sliced = my_list[::3] # Returns [0, 1, 3, 4]
A negative step value (e.g., -1
) skips indices in reverse
Example: step=-2
selects every second element in reverse order.
my_list = [0, 1, 2, 3, 4, 5]
sliced = my_list[::-2] # Returns [5, 3, 1]
Example: step=
-3 means every third element is taken in reverse order.
my_list = [0, 1, 2, 3, 4, 5]
sliced = my_list[::-3] # Returns [5, 4, 2, 1]