Skip to content

Python List comprehension double for loop | Example code

  • by

Simply do the 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)]



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]


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]


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

Do comment if you have any doubts or suggestions on this Python List loop topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *

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