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
.