Python list comprehension multiple variables | Example code

Using a list comprehension to iterate through two variables at the same time increasing the loop position in both at the same time.

Given lists

a = [1,2,3,4,5]

b = [6,7,8,9,10]

Expecting Output: c = [7, 9, 11, 13, 15]

Example list comprehension multiple variables

Doing this operation with list comprehension is not a good option instead use below coe.

Using the sum function

a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9, 10]

c = map(sum, zip(a, b))
print(list(c))

Using the map is a function

a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9, 10]

c = [aa + bb for aa, bb in zip(a, b)]
print(c)

Output:

Python list comprehension multiple variables

Multiple variables in for loop list comprehension

This is called unpacking. If the list (or any other iterable) contains two-element iterable, 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)]

final result would be

res = [3, 7, 10]

Something like:

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

Python list comprehension to produce two values in one iteration

Use itertools.chain.from_iterable:

from itertools import chain

res = list(chain.from_iterable((i, i ** 2) for i in range(1, 6)))

print(res)

Output: [1, 1, 2, 4, 3, 9, 4, 16, 5, 25]

List comprehensions can have multiple clauses.

res = [10 * x + y for x in range(4) for y in range(3)]

print(res)

Output: [0, 1, 2, 10, 11, 12, 20, 21, 22, 30, 31, 32]

Do comment if you have any doubts and suggestions on this Python List topic,

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.