Collections

Slices

Slices copy meaningful ranges from ordered sequences.

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']
abcdef0123456[:3][3:]
Slice indices sit between cells; [:3] and [3:] partition the sequence at index 3, never overlapping or losing an item.

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

See also

Run the complete example

Example code

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.