0

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?

Oleksandr Novik
  • 489
  • 9
  • 24

3 Answers3

2

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.

ma4strong
  • 300
  • 2
  • 8
1

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.

Zen
  • 115
  • 7
0

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)]
Barmar
  • 741,623
  • 53
  • 500
  • 612