Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple variable in for loop list comprehension

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.

like image 292
Masquerade Avatar asked Dec 24 '22 21:12

Masquerade


2 Answers

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, ...].

like image 90
Rushy Panchal Avatar answered Feb 23 '23 05:02

Rushy Panchal


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]
like image 22
nu11p01n73R Avatar answered Feb 23 '23 05:02

nu11p01n73R