Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Sequences Sequence Iteration Iterating with Enumerate

Pedro Leitao
Pedro Leitao
1,436 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,021 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,436 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!