3

I'm currently reading some online Python stuff and something interesting popped up. Basically it says not to do this:

for i in range(len(mylist)):
    print i, mylist[i]

Instead it says that it is better to do this:

for (i, item) in enumerate(mylist):
    print i, item

Normally I would go with the first option, but I don't see any potential risks involved in doing this. Why is the first code bad? Could the first body of code have some kind of effect on proceeding lines of code compared to the latter?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Belphegor
  • 1,683
  • 4
  • 23
  • 44

1 Answers1

5

Aside from the readability factor, the 2nd snippet works on any iterable, whereas the first only works on objects that can be indexed (e.g. lists). For example, imagine if you were using a set:

>>> myset = {1,2,3}
>>>
>>> enumerate(myset)  # works
<enumerate object at 0x2c9440>
>>>
>>> myset[0]          # doesn't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support indexing

This adds flexibility to the code, and makes your life easier should you ever choose to switch data structures.

arshajii
  • 127,459
  • 24
  • 238
  • 287