This forum is now read-only. Please use our new forums at discuss.codecademy.com.

1551 points
A8b653d55ea88c906c45017924f947d6?s=140&d=retro
Submitted by
Abuzz
about 6 years ago

So what exactly does enumerate do?

All of a sudden the for loop includes index, item.

Not sure what enumerate does or the comma in the for loop.


44 votes

permalink

enumerate() is one of the built-in Python functions. It returns an enumerate object. In our case that object is a list of tuples (immutable lists), each containing a pair of count/index and value. Look at http://docs.python.org/library/functions.html?highlight=enumerate#enumerate

Try the following in the python labs
(here we use another built-in function list([iterable]) which returns a list whose items are the same and in the same order as iterable‘s items).

>>> choices = ['pizza', 'pasta', 'salad', 'nachos']
>>> list(enumerate(choices))
=> [(0, 'pizza'), (1, 'pasta'), (2, 'salad'), (3, 'nachos')]

So, in the for index, item in enumerate(choices): expression index, item is the pair of count, value of each tuple: (0, 'pizza'), (1, 'pasta'), ...

We may easily change the start count/index with help of enumerate(sequence, start=0)

for index, item in enumerate(choices, start = 1):
    print index, item

or simply with a number as the second parameter

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

in opposite to the lesson's hint

for index, item in enumerate(choices):
    print index + 1, item

1595 points
50faf88e46ce3ec6a6000c33_424995552
Submitted by
Ivan Chernikov
about 6 years ago

8 Comments

Picture Alex J about 6 years ago

Great explanation, Ivan! Did you know you can link to code examples in the Labs by clicking "share" in the upper right corner? See http://labs.codeacademy.com/4eL#:workspace

A8b653d55ea88c906c45017924f947d6?s=140&d=retro Abuzz about 6 years ago

Thanks!! Understand it much better now.

50faf88e46ce3ec6a6000c33_424995552 Ivan Chernikov about 6 years ago

@ Alex J. I see, I will be sharing code examples in the Labs then :-)

Eb36e6c02dd237647a4966566b73fe5b?s=140&d=retro franchoo almost 6 years ago

Genius! Ty

Cf44f2e0bbd92fef9179befd1d111958?s=140&d=retro achillesc2 almost 6 years ago

this is exactly what i needed - it was not explained at all. Thank you so much!

Dacdc855575f2be754e8316d046e3549?s=140&d=retro munderbrink over 4 years ago

The lesson should be updated to better explain the enumerate.

B6137211f4788ec282472d286cbfd4ca?s=140&d=retro j.sitruk over 4 years ago

Thank you very much for the comment. It was true that seeing this 'index, item' pair was quite confusing. Thanks for the help!

6ca1a7d11bc1d624a59fc4ea84caec46?s=140&d=retro Aditya Agnihotri over 3 years ago

Thanks for explanation! Above mentioned details should be included in the tutorial.