-2

If we assume a and b both contain 5 integers:

temp = [ x for x in zip(a, b) ]

What is the difference between these two pieces of code? Why does this work:

for q, p in temp:
    pass

But not this?

q = [ x for x, _ in temp ]
p = [ x for _, x in temp ]

The second fails with ValueError: not enough values to unpack (expected 2, got 1).

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Bro K
  • 43
  • 7

2 Answers2

1

Here's how it works.

Let's say

a = range(1,6)
b = range(3,8)

temp = [ x for x in zip(a, b) ]

Here, x will get a tuple. It will have each element from a and b sent to x. So the result of this will be:

[(1, 3), (2, 4), (3, 5), (4, 6), (5, 7)]

If you want each value from the for loop to be stored in different variables, you can give:

temp = [(p,q) for p,q in zip(a, b)]

Here, p will get values 1, 2, 3, 4, 5 and q will get values 3, 4, 5, 6, 7

The result of both the list comprehensions are the same.

Now let's look at the other two.

q = [ x for x, _ in temp ]
p = [ x for _, x in temp ]

Here, the code is trying to pick values from temp which has tuples. Each iteration, two values are retrieved. For the code

q = [ x for x, _ in temp ]

it is retaining the first value into x and discarding the second value. So list q will have [1, 2, 3, 4, 5].

Similarly, for p, it discards the first value while retaining the second value. So list p will have [3, 4, 5, 6, 7]

And lastly, when you look at

for q, p in temp:
    pass

You are iterating through temp but you are not storing the values anywhere. So once all the values in temp are iterated thru, the values of q and p will be the last element of temp which will be (5,7). This will result in q getting 5 and p getting 7.

Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33
-1

The first one is list comprehension and other one is simple for loop. List comprehension is an easy way to run some loop or some conditions and it rerurns a list.

So in your example, temp will be a list.

We also have dict comprehension which returns dictionary

Irfan wani
  • 4,084
  • 2
  • 19
  • 34