4

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.

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Any iterable of two elements.
3

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]

3 Comments

Compare it with variable unpacking; a, b = x
@Jollywatt Sorry I didn't get you. a, b = x will work as long as x has two elements
Apologies. I was suggesting you mention that this is all an example of variable unpacking, which is the underlying concept. Just so that the OP would realise the relationship between a, b in x and a, b = x. :)
2

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)]

Comments

2

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)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.