Collections
Slices
Omitted bounds mean “from the beginning” or “through the end.” Because the stop index is excluded, adjacent slices split a sequence cleanly.
Source
letters = ["a", "b", "c", "d", "e", "f"]
first_page = letters[:3]
rest = letters[3:]
print(first_page)
print(rest)Output
['a', 'b', 'c']
['d', 'e', 'f']Use start:stop for a middle range and step when you want to skip or walk backward. These operations return new lists; the original list is unchanged.
Source
middle = letters[1:5]
every_other = letters[::2]
reversed_letters = letters[::-1]
print(middle)
print(every_other)
print(reversed_letters)
print(letters)Output
['b', 'c', 'd', 'e']
['a', 'c', 'e']
['f', 'e', 'd', 'c', 'b', 'a']
['a', 'b', 'c', 'd', 'e', 'f']Notes
- Slice stop indexes are excluded, so adjacent ranges compose cleanly.
- Omitted bounds mean the beginning or end of the sequence.
- A negative step walks backward;
[::-1]is a common reversed-copy idiom.
See also
Run the complete example
Expected output
['a', 'b', 'c']
['d', 'e', 'f']
['b', 'c', 'd', 'e']
['a', 'c', 'e']
['f', 'e', 'd', 'c', 'b', 'a']
['a', 'b', 'c', 'd', 'e', 'f']
Execution time appears here after you run the example.