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 trialPedro Leitao
1,615 PointsWhy 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
Treehouse Moderator 11,075 PointsWell 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
1,615 PointsPedro Leitao
1,615 PointsThanks 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"
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"
I would naturally use the enumerate function like that:
Thank You again!