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)] print(list1)
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 or suggestions on this Python List loop topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.