Reputation: 3890
What is the meaning of the following line of code?
arr = [a+b for a,b in list]
Generally a 'for' loop is used with a single variable (in this case 'i')
arr = [i for i in list]
In the first case multiple variables 'a' and 'b' are used inside the for loop, which I am unable to understand. Please explain this format.
Upvotes: 4
Views: 6537
Reputation: 26667
The elements of the list
are tuples/list with 2 elements and when we write,
a,b in x
we unpack each element to two different variables, a
and b
>>> a,b = [1, 2]
>>> a
1
>>> b
2
Example
>>> x = [ (i, i*i) for i in range(5) ]
>>> x
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)]
>>> [ a+b for a,b in x ]
[0, 2, 6, 12, 20]
Upvotes: 3
Reputation: 114240
This is called unpacking. If the list (or any other iterable) contains two-element iterables, they can be unpacked so the individual elements can be accessed as a
and b
.
For example, if list
was defined as
list = [(1, 2), (3, 4), (4, 6)]
your final result would be
arr = [3, 7, 10]
You can unpack as many elements as you need to into as many variables as you need. The only catch is that all the elements of the list must be the same length for this to work (since you are specifying the number of variables to unpack into up front).
A more common usage of this construction (possibly the most common I have seen) is with enumerate
, which returns a tuple with the index as well as the item from an iterable. Something like:
arr = [ind + item for ind, item in enumerate(numbers)]
Upvotes: 2
Reputation: 11034
What's going on is called tuple unpacking.
Each element in list
should be a tuple or some other equivalent sequence type which can be unpacked.
Example:
l = [(1, 2), (3, 4)]
arr = [a + b for a, b in l]
print(arr)
Output:
[3, 7] # [(1+2), (3+4)]
Upvotes: 2
Reputation: 17532
for a,b in list
deconstructs a list of tuples (or a list of two elements). That is, list
is expected to be of the form [(a0, b0), (a1, b1), ...]
.
So, [a+b for a,b in list]
results in [a0+b0, a1+b1, ...]
.
Upvotes: 4