1
for index, item in enumerate(things):
    print index, item

We can access to the item through the index:

for index in range(len(things)):
    print index, things[index]

With the second example we have a variable less, but the same power

Superluminal
  • 947
  • 10
  • 23
  • I am not checking this so don't take my answer for granted, but afaik `enumerate` is much faster than `for in range()`. Although it depends what you mean by benefits – RMS Dec 07 '16 at 13:22
  • 3
    https://www.python.org/dev/peps/pep-0279/ – Lafexlos Dec 07 '16 at 13:24
  • I would guess that in python 3 both should be more or less identical, since range also works as an generator. – Sosel Dec 07 '16 at 13:24
  • 3
    I checked @Roxanne's answer, and indeed `enumerate()` is faster than `range(len())` on a list of 1,000,000 floats. 270 ns vs 9.19 ms. – jkr Dec 07 '16 at 13:24
  • 4
    [Pythonic: range vs enumerate in python for loop](http://stackoverflow.com/questions/24150762/pythonic-range-vs-enumerate-in-python-for-loop) and [What is faster for loop using enumerate or for loop using xrange in Python?](http://stackoverflow.com/questions/4852944/what-is-faster-for-loop-using-enumerate-or-for-loop-using-xrange-in-python) – Chris_Rands Dec 07 '16 at 13:26
  • FYI `range` in Python3 is `xrange` in Python2. Both are generators. – jkr Dec 07 '16 at 13:27
  • @Jakub I just tried this myself, I did not really find a significant difference between enumerate and range in python3 (on a numpy array as "things") – Sosel Dec 07 '16 at 13:32
  • _With the second example we have a variable less, but the same power_ Who said that less variables means a better code? – Łukasz Rogalski Dec 07 '16 at 13:37
  • @Sosel I am using Python2. I reran the code and included `xrange` (which replaces `range` in Python3). There was no real difference between `xrange(len())` and `enumerate()`. 293 ns vs 256 ns. – jkr Dec 07 '16 at 13:40
  • The main advantage is **clear intent** expressed by code. `enumerate` means iterating with indices. `zip` means iterating pairwise. Not having to manage counters manually (via range objects) **is** an advantage. You duplicate information in two places. What if you refactor a code, rename `things` and change that name only in one place? – Łukasz Rogalski Dec 07 '16 at 13:45

0 Answers0