Slicing of List in Python
Slicing allows us to extract a sub-list (a portion of list items) by specifying a range of indices. It uses the start:end:step notation.
Syntax list[start:end:step]
- start → index where the slice begins (inclusive). Default = 0.
- end → index where the slice stops (exclusive). Default = len(list).
- step → difference between indices (skip value). Default = 1.
Example:
Python
# Example list numbers = [10, 20, 30, 40, 50, 60, 70, 80] # 1. Basic slicing print(numbers[2:5]) # [30, 40, 50] → elements from index 2 to 4 # 2. Omitting start index print(numbers[:4]) # [10, 20, 30, 40] → from beginning to index 3 # 3. Omitting end index print(numbers[3:]) # [40, 50, 60, 70, 80] → from index 3 to end # 4. Using step print(numbers[1:7:2]) # [20, 40, 60] → every 2nd element between 1 and 6 # 5. Negative indices print(numbers[-4:]) # [50, 60, 70, 80] → last 4 elements # 6. Reverse slicing print(numbers[::-1]) # [80, 70, 60, 50, 40, 30, 20, 10] → reversed list # 7. Slice with negative step print(numbers[7:2:-2]) # [80, 60, 40] → from index 7 to 3, skipping backwards