Skip to main content
The 2026 Annual Developer Survey is live— take the Survey today!

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.

3
  • 3
    The this_is_how_slicing_works is not the same as python slice. E.G. [0, 1, 2][-5:3:3] will get [0] in python, but list(this_is_how_slicing_works([0, 1, 2], -5, 3, 3)) get [1]. Commented Oct 29, 2016 at 12:56
  • @Eastsun Oops, you're right! A clearer case: range(4)[-200:200:3] == [0, 3] but list(this_is_how_slicing_works([0, 1, 2, 3], -200, 200, 3)) == [2]. My if 0 <= i < len(seq): was an attempt to implement "never go outside the sequence" simply but is wrong for step>1. I'll rewrite it later today (with tests). Commented Oct 30, 2016 at 12:36
  • If you're implementing a custom __getitem__(self, key) yourself, you don't have to handle all that. slice objects have a .indices(L) method doing all these adjustments for you, and since range() itself is now cheap and indexable you can simplify it to just: for i in range(L)[key]: .... Commented Mar 13, 2025 at 15:11

lang-py