Home > other >  Two for loops in list comprehension produce weird output in Python
Two for loops in list comprehension produce weird output in Python

Time:11-24

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?

CodePudding user response:

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.

CodePudding user response:

There are two things happening here.

First: print([x**2 for x in l1...

This is taking each of the elements in l1 and squaring them producing [1, 4, 9, 16]

Second: ... for y in l2])

This is repeating this process (squaring and printing the element in l1) one time for each value in l2 which is why you are getting 4 of each squared value.

CodePudding user response:

Your list comprehension is equivalent to the following for loops:

result = []
for y in l2:
    for x in l1:
        result.append(x**2)

From this you can see why the inner loop is repeating 4 times.

If you want to loop over the two lists in parallel, not nested, use zip():

[x**2 for x, y in zip(l1, l2)]
  • Related