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 Comprehensions

List Comprehensions: multiple "for" loops

Hi, Kenneth Love

Would it be better/more readable if the list comprehension you show at 6 min in to the video (as well as the row and cols one shown before this) was written with its "for... in" loops in the order of the variables? Like:

[(letter, number) for letter in 'abc' for number in range(1, 5)]

And when you're talking about "inner" and "outer" in the example before this one, I assume you're talking about the first 'for' loop being the "outer" one and the second 'for' loop being the "inner" one, right?

For instance, "[(letter, number) for letter in 'abc' for number in range(1, 5)]"... is like typing this:

for letter in 'abc':         # Outer
    for number in range(1, 5):     # Inner (nested inside of the outer one)
        # do something here

where the code takes the 'a' and matches it with 1, 2, 3, etc... and then takes the 'b' and does likewise, right?

Thanks, D.

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Better? I dunno, maybe. It's handy to see/know, though, that even though the variables come out in one order you can use them in another. Often you'll find that you can't easily swap the loop order around.

Thanks for the comment!

Oh, ok... thanks, Kenneth! Been enjoying your teaching... very helpful!