Search code examples
pythonlistfor-looplist-comprehension

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?


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.