Reputation: 637
This is two for loop code, where the inner loop depends upon the first loop. When I tried to create list compression it gives the wrong result. Please suggest what is missing.
for i in range(5):
for j in range(i):
print(j, end=', ')
print()
print([j for j in range(i) for i in range(5)])
Output:
0, 0, 1, 0, 1, 2, 0, 1, 2, 3,
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]
Thanks!!!
Upvotes: 0
Views: 1794
Reputation: 531075
Where you read the for loops from top to bottom, you read the generators from left to right in the list comprehension.
# outer/first inner/second
>>> print([j for i in range(5) for j in range(i)])
[0, 0, 1, 0, 1, 2, 0, 1, 2, 3]
The example you use in your question only works because i
is still defined from the previous for
loops when you run range(i)
. If you tried to run that in a fresh interpreter, you would get a NameError
on i
.
Upvotes: 2