List Slicing in Python
List slicing allows you to extract a portion (slice) of a list by specifying a range of indices. It allows you to access parts of a list without modifying the original list.
Syntax
list[start:end:step]
Where,
start (Optional): The index where the slice begins (inclusive). If omitted, it defaults to 0 (the beginning of the list).
end (Optional): The index where the slice stops (exclusive). If omitted, it defaults to the length of the list.
step (Optional): The interval between items.
Example:
numbers = [10, 20, 30, 40, 50, 60, 70]
# Get items from index 1 up to (but not including) index 5
slice = numbers[1:5]
print(slice) # Output: [20, 30, 40, 50]
Indices in Python start at position 0, meaning the first item is at index 0, the second at index 1 and so on.
Also, notice that list slicing always includes the item at start index but excludes the item at end index.
Omitting the start Parameter
If you omit the start parameter, the slice begins from the start of the list (i.e., index 0).
For example:
numbers = [10, 20, 30, 40, 50, 60, 70]
# Get items from the beginning up to (but not including) index 5
slice = numbers[:5]
print(slice) # Output: [10, 20, 30, 40, 50]
Omitting the end Parameter
If you omit the end parameter, the slicing continues until the end of the list.
For example:
numbers = [10, 20, 30, 40, 50, 60, 70]
# Get items from index 3 to the end of the list
slice = numbers[3:]
print(slice) # Output: [40, 50, 60, 70]
Using Negative Indices
List slicing also supports negative indexing, which allows you to count items from the end of the list. The last item is at index -1, the second last at index -2, and so on.
For example:
numbers = [10, 20, 30, 40, 50, 60, 70]
# Get the last three items
slice1 = numbers[-3:]
print(slice1) # Output: [50, 60, 70]
# Get items from index -5 to -2
slice2 = numbers[-5:-2]
print(slice2) # Output: [30, 40, 50]
Step Parameter
The step parameter determines how many items to skip between each item in the slice.
For example:
numbers = [10, 20, 30, 40, 50, 60, 70]
# Get every second items from index 1 to the end
slice = numbers[1::2]
print(slice) # Output: [20, 40, 60]
Omitting All Parameters
If all parameters are omitted, the slice returns a copy of the entire list.
For example:
numbers = [10, 20, 30, 40, 50, 60, 70]
slice = numbers[:]
print(slice) # Output: [10, 20, 30, 40, 50, 60, 70]
Negative Step
A negative step in list slicing means the list is traversed in reverse order – from right to left.
Example: Reverse the whole list
numbers = [10, 20, 30, 40, 50, 60, 70]
# Reverse the entire list
slice = numbers[::-1]
print(slice) # Output: [70, 60, 50, 40, 30, 20, 10]
Example: Slice backwards from a specific index
numbers = [10, 20, 30, 40, 50, 60, 70]
slice = numbers[5:1:-1]
print(slice) # Output: [60, 50, 40, 30]
When using a negative step, the start index should be greater than the stop index, otherwise, the result will be an empty list.