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.
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, ...]
.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With