Python Glossary Русский

all Python 3Lists (list)term

List slicing

indexing/slicing

Slices return a new list. s[a:b:c] takes step c. [::-1] reverses it. A slice with no arguments is a shallow copy.

Syntax

lst[a:b]  |  lst[a:b:c]  |  lst[::-1]

Slicing never fails on bounds: for a short list lst[5:100] simply returns an empty list — unlike lst[5], which raises IndexError. The copy is shallow: nested lists are shared objects, so mutating one is visible through the other; use copy.deepcopy() for an independent copy. Assigning to a slice (lst[1:3] = [...]) mutates the original list and can change its length.

Examples

lst = [0, 1, 2, 3, 4, 5]
print(lst[1:4])
# → [1, 2, 3]
print(lst[:3])
# → [0, 1, 2]
print(lst[3:])
# → [3, 4, 5]
print(lst[::-1])
# → [5, 4, 3, 2, 1, 0]
print(lst[::2])
# → [0, 2, 4]
copy = lst[:]
print(copy is lst)
# → False (новый объект)
lst[1:4] = [10, 20, 30]
print(lst)
# → [0, 10, 20, 30, 4, 5]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy