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

Two for loops in list comprehension produce weird output in Python

I’ve written this code:

l1 = [1, 2, 3, 4]
l2 = [5, 6, 7, 8]

print([x**2 for x in l1 for y in l2])

which outputs this:

[1, 1, 1, 1, 4, 4, 4, 4, 9, 9, 9, 9, 16, 16, 16, 16]

My question is, what is happening inside this list comprehension? Why is the amount of items in l1 multiplied by the length of l2?

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 :

It’s like you do:

for x in l1:
   for y in l2: #this loop has len(l2) iteration
      print(x**2)

In the y loop, you only use variable x, which doesn’t change for len(l2) iterations.

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