Python Glossary Русский

all Python 3Lists (list)term

Slices with a step [::2] / [::-1]

indexing/slicing

The third slice parameter is the step: [start:stop:step]. Step 2 takes every second item. Step -1 gives the reverse order. start/stop can be combined with a step.

Syntax

lst[start:stop:step]

With a negative step the defaults flip — the slice runs from the end backwards, yet stop is still excluded, so lst[3:0:-1] gives items 3, 2, 1 and drops index 0. A zero step is forbidden: lst[::0] raises ValueError. Do not confuse lst[::-1] with list.reverse(): the slice builds a new copy, while reverse() flips the list in place and returns None.

Examples

lst = [0, 1, 2, 3, 4, 5, 6]
print(lst[::2])     # → [0, 2, 4, 6]
print(lst[::-1])    # → [6, 5, 4, 3, 2, 1, 0]
print(lst[1::2])    # → [1, 3, 5]
print(lst[6:0:-2])  # → [6, 4, 2]
print(lst[:4:1])    # → [0, 1, 2, 3]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy