You can write more fast and more compact code using 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
A 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:
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]
Please comment if you have any doubts or suggestions on this Python Nested 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.