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.

8
  • 147
    As Aaron points out below, use start=1 if you want to get 1-5 instead of 0-4.
    – clozach
    Commented Mar 31, 2018 at 22:16
  • 12
    Does enumerate not incur another overhead? Commented Oct 17, 2019 at 23:03
  • 12
    @TheRealChx101 according to my tests (Python 3.6.3) the difference is negligible and sometimes even in favour of enumerate. Commented Feb 7, 2020 at 12:18
  • 29
    @TheRealChx101: It's lower than the overhead of looping over a range and indexing each time, and lower than manually tracking and updating the index separately. enumerate with unpacking is heavily optimized (if the tuples are unpacked to names as in the provided example, it reuses the same tuple each loop to avoid even the cost of freelist lookup, it has an optimized code path for when the index fits in ssize_t that performs cheap in-register math, bypassing Python level math operations, and it avoids indexing the list at the Python level, which is more expensive than you'd think). Commented Oct 6, 2020 at 18:19
  • 10
    @user2585501. It does: for i in range(5) or for i in range(len(ints)) will do the universally common operation of iterating over an index. But if you want both the item and the index, enumerate is a very useful syntax. I use it all the time.
    – bfris
    Commented Oct 14, 2021 at 19:10