Python List comprehension double for loop | Example code

Simple do Outermost loop comes first, and then the inner loops subsequently to get List comprehension double for loop in Python.

The list comprehension should be like this:

[x for b in a for x in b]

Example List comprehension double for loop in Python

Simple example code.

list1 = [(x, y) for x in range(0, 3) for y in range(0, 1)]

print(list1)

Output:

Python List comprehension double for loop

Another example

z = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
res = [x for y in z if sum(y) > 10 for x in y if x < 10]

print(res)

Output: [5, 6, 7, 8, 9]

How to do a double iteration with list comprehension in Python?

Answer: Use a list comprehension to do a double iteration.

text = [["Hello", "World!"], ["Whats", "Up!"]]

res = [word for words in text for word in words]

print(res)

Output: [‘Hello’, ‘World!’, ‘Whats’, ‘Up!’]

Do comment if you have any doubts and suggestions on this Python List loop 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.