Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How list comprehension works for two for loop?

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!!!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading