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 Collections (Retired) Tuples Tuples With Functions

peter keves
peter keves
6,854 Points

can 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

Right, 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 prints 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! (:

So 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?