Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

How slicing in Python works

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?


See Why are slice and range upper-bound exclusive? to learn why xs[0:2] == [xs[0], xs[1]], not [..., xs[2]].
See Make a new list containing every Nth item in the original list for xs[::N].
See How does assignment work with list slices? to learn what xs[0:2] = ["a", "b"] does.

Answer*

Cancel
2
  • @WinEunuuchs2Unix that's great feedback - this is a standard Python behavior, but it could be made clearer in that sort of way, so I'll consider updating my material to include this semantic.
    – Aaron Hall
    Commented Sep 30, 2020 at 1:37
  • Your answer is the only one (?) that touches the tip of what would be interesting here, when you write "slicable" - the rest is triviality. I wanted to know how the slicing is done, using the __getitem__ method. But if I understand well, you have to do all of it on your own: check whether the arg to your __getitem__ is an int or a slice (or what else could it be?), and in that (slice) case, deal with all possible cases ((A) or (A,B) or (A,B,C), and all possible sign combinations) on your own.... is that right?
    – Max
    Commented Nov 29, 2022 at 21:09