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

Alex Rendon
Alex Rendon
7,498 Points

Why two variables in the for loop?

I don't understand why there are two variables instead of one variable (in the for loop).

for variable1, variable2 in enumerate(list): ... ...(code)

2 Answers

What enumerate does is essentially assigns var1 and var2 two separate pieces of information.

If you were to write :

for index, items in enumerate(a_list): blah blah blah

basically what is happening is that enumerate is assigning the index of the list to the variable "index" and the item at that index to the variable "items" This is useful because every time the loop runs again, the index is increased by one and therefore the item is the next item in the list.

so, instead of doing something like this:

count = 0

for items in a_list: print(a_list[count]) count += 1

you can do this:

for idx, items in enumerate(a_list): print(a_list[idx])

or some variation. It essentially saves you some variable declaration

Alex Rendon
Alex Rendon
7,498 Points

Thanks so much, now i understand it. :)

Seth Kroger
Seth Kroger
56,414 Points

You're using two variables because enumerate() returns two values in each step as a tuple instead of just a single value.