List comprehension nested for loop | Example code

  • by

You can write more fast and compact code using the list compression and nested loop in Python.

lst = [j + k for j in s1 for k in s2]

OR

lst = [(j, k) for j in s1 for k in s2]

Example List comprehension nested for loop

Simple example code uses two for loops in list Comprehension and the final result would be a list of lists. we will not include the same numbers in each list. we will filter them using an if condition.

final = [[x, y] for x in [10, 20, 30] for y in [30, 10, 50] if x != y]
print(final)

Output:

List comprehension nested for loop

Another example combination of lists

first = [2, 3, 4]
second = [1, 0, 5]

final = [i + j for i in first for j in second]

print(final)

Output:

[3, 2, 7, 4, 3, 8, 5, 4, 9]

Nested List Comprehension to flatten a given 2-D matrix

# 2-D List
matrix = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]

res = [val for sublist in matrix for val in sublist]

print(res)

Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Do comment if you have any doubts and suggestions on this Python Nested Loop topic.

Note: IDE: PyCharm 2021.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.