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 trialpeter keves
6,854 Pointscan someone explain to me what did he do at 2:58 and all the things with step[0] step[1]
can someone explain to me what did he do at 2:58 and all the things with step[0] step[1]
1 Answer
Anderson Leonardo
Courses Plus Student 2,002 PointsRight, you know that enumerate()
takes a list and returns an enumerate object containing tuples with the elements of that list numbered according to their indexes, i.e.:
animals = ["bird", "turtle", "cat"]
new_animals_list = list( enumerate(animals) )
# new_animals_list = [ (0, "bird"), (1, "turtle"), (2, "cat") ]
When the teacher uses enumerate()
in that loop, he print
s each one of the function's return value separately. Just like I'll do with my animals
list:
for animal in enumerate(animals):
print("{}: {}".format(animal[0], animal[1]))
When the loop runs for the first time, animal
will be the following tuple: (0, "bird")
. Using index notation, I access the tuple's elements (animal[0]
and animal[1]
).
Finally, the .format()
method takes what's inside the parenthesis and replace the curly brackets ({}
) in the string. The first pair of curly brackets is replaced by animal[0]
, that is 0
, while the second pair is replaced by animal[1]
, that is "bird"
.
The same happens to the tuples (1, "turtle")
and (2, "cat")
.
# Which results in:
# 0: bird
# 1: turtle
# 2: cat
Hope that helps! (:
Anna Grais
12,743 PointsAnna Grais
12,743 PointsSo because of enumerate, step[0] = the index and step[1] = the value of that index?
Because otherwise you would think that step[0] would call the value, with the index 0, and step[1] would call the value, with the index 1?
Wait I think I understand it now. By printing a list with enumerate, it creates tuples out of those list items. Those tuples consist of both the list item, and the index it had. The index is now also its own item in the tuple. That's why you can call it with step[0] because it have gotten its own index now.
Right?