How slicing in Python works

Asked 2023-09-20 20:06:12 View 52,755

How does Python's slice notation work? That is: when I write code like a[x:y:z], a[:], a[::2] etc., how can I understand which elements end up in the slice? Please include references where appropriate.


See Why are slice and range upper-bound exclusive? for more discussion of the design decisions behind the notation.

See Pythonic way to return list of every nth item in a larger list for the most common practical usage of slicing (and other ways to solve the problem): getting every Nth element of a list. Please use that question instead as a duplicate target where appropriate.

For more specific answers about slice assignment, see How does assignment work with list slices? (although this is also addressed here).

Answers