Loading...
Loading...
Extract portions of lists with slicing
Slicing lets you grab any portion of a list ā the first 3 items, the last 2, every other item, everything except the ends. It's one of Python's most elegant features.
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[2:6]) # [2, 3, 4, 5] ā start at 2, stop BEFORE 6
print(nums[:4]) # [0, 1, 2, 3] ā start at beginning
print(nums[6:]) # [6, 7, 8, 9] ā go to end
print(nums[::2]) # [0, 2, 4, 6, 8] ā every 2nd item
print(nums[::-1]) # [9, 8, 7, 6, ...] ā reversed copy!| Slice | What it does |
|---|---|
| `list[start:stop]` | Items from `start` to `stop-1` |
| `list[:stop]` | Items from beginning to `stop-1` |
| `list[start:]` | Items from `start` to end |
| `list[:]` | Copy of the entire list |
| `list[start:stop:step]` | Every `step`-th item in range |
| `list[::-1]` | Reversed copy |
letters = ["a", "b", "c", "d", "e", "f"]
# 0 1 2 3 4 5
print(letters[1:4]) # ["b", "c", "d"] ā items at index 1, 2, 3
print(letters[-3:]) # ["d", "e", "f"] ā last 3 items
print(letters[1:5:2]) # ["b", "d"] ā every 2nd from index 1 to 4nums = [1, 2, 3, 4, 5]
subset = nums[1:3] # [2, 3] ā a NEW list
print(nums) # [1, 2, 3, 4, 5] ā unchanged!| ā Wrong | Why | ā Right |
|---|---|---|
| `list[2:6]` expecting to include index 6 | Stop index is exclusive | Use `list[2:7]` to include index 6 |
| `list[5:2]` | Start > stop with positive step = empty list | Use `list[5:2:-1]` to go backward |
| `list[1:3] = [100]` | Replaces items, doesn't return them | Use `list[1:3]` for reading |
Create a list: nums = [10, 20, 30, 40, 50, 60, 70, 80]. Then:
nums = [10, 20, 30, 40, 50, 60, 70, 80] print(nums[:4]) print(nums[-3:]) print(nums[::2]) print(nums[::-1])