Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Sequences Sequence Iteration Iterating with Enumerate

Pedro Leitao
Pedro Leitao
1,615 Points

Why does she use "index" with the "Enumerate function"?

Why is it typed

for index, item in enumerate(groceries, 1):
    print(f"{index}. {item}")

instead of

for item in enumerate(groceries, 1):
    print(item)

Indeed the output gets a bit different, I am struggling to understand the purpose of "index" though

I don't understand how "index" is getting related to "groceries" and to "Enumerate function"

Thank you all

1 Answer

Dane Parchment
MOD
Dane Parchment
Treehouse Moderator 11,074 Points

Well you do enumeration in python when you want to keep track of the amount of iterations you are performing, mostly if you need to use them for some form of formatting. Usually you'd have to use other methods for that (a variable that keep track of numbers, indexes in an array, etc.). Python makes this easier to do by having this built in enumerate method.

So basically, the index is basically the most important aspect of it. Yes, you can use the for..in loop to iterate through an iterable object. But the enumerate method will help you keep track of the iterations taking place, and will help format it for you, by even selecting a starting point (eliminating the 0 index issue for lists/dictionaries for example).

Pedro Leitao
Pedro Leitao
1,615 Points

Thanks for your explanation!

But what I don't get is...

That was her first example of a method to enumerate the items in the list. which I do understand the purpose of "index"

groceries = ['roast beef', 'cucumbers', 'lettuce', 'peanut butter', 'bread', 'dog food']

index = 1

for item in enumerate(groceries, 1):
    print(f"{index}. {item}")
      index +=1

That was her second example of a method to enumerate the items in the list. Which I do understand the purpose of the function "enumerate", but not the purpose of the "index"

groceries = ['roast beef', 'cucumbers', 'lettuce', 'peanut butter', 'bread', 'dog food']

for index, item in enumerate(groceries, 1):
    print(f"{index}. {item}")

I would naturally use the enumerate function like that:

groceries = ['roast beef', 'cucumbers', 'lettuce', 'peanut butter', 'bread', 'dog food']

for item in enumerate(groceries, 1):
    print(item)

Thank You again!