Multiple variable to define a loop list

What is the meaning of the following line of code?

arr = [a+b for a,b in list]

Usually the for loop is used with one variable (in this case, the i)

arr = [i for i in list] 

In the first case, the for loop uses several variables "a" and "b", which I cannot understand. Please explain this format.

+4
source share
4 answers

This is called unpacking. If the list (or any other iterable) contains two-element iterations, they can be unpacked, so individual elements can be accessed like aand b.

For example, if it listwas defined as

list = [(1, 2), (3, 4), (4, 6)]

your end result will be

arr = [3, 7, 10]

, , , . , , ( , ).

(, ) enumerate, , . - :

arr = [ind + item for ind, item in enumerate(numbers)]
+2

for a,b in list ( ). , list [(a0, b0), (a1, b1), ...].

, [a+b for a,b in list] [a0+b0, a1+b1, ...].

+3

list / 2 , ,

 a,b in x

, a b

>>> a,b = [1, 2]
>>> a
1
>>> b
2

>>> 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]
+3

What happens is called tuple unpacking. Each element in listmust be a tuple or some other equivalent type of sequence that can be unpacked.

Example:

l = [(1, 2), (3, 4)]
arr = [a + b  for a, b in l]
print(arr)

Conclusion:

[3, 7]    # [(1+2), (3+4)]
+2
source

Source: https://habr.com/ru/post/1666577/


All Articles