Multiple Loops in List Comprehension in Python
Working with inclusion allows you to write several cycles to generate a new list. The first specified cycle will be external, in which the second written cycle will be launched. This means that the second cycle will be nested in the first.
Let's form a list of tuples. To do this, we first write two variables i
and j
, enclosed in parentheses denoting a tuple. Next, we run a loop with the variable i
, which should generate the first number from the tuple in the range from 1
to 3
. Then we write a loop, where the second number j
is generated from 1
to 2
:
lst = [(i, j) for i in range(1, 4) for j in range(1, 3)]
print(lst)
Result of code execution:
[(1, 1), (1, 2), (2, 1), (2, 2), (3, 1), (3, 2)]
Two lists are given:
lst1 = ['1', '2']
lst2 = ['a', 'b', 'c']
Use the inclusion to make a new list from them:
[('1', 'a'), ('1', 'b'), ('1', 'c'), ('2', 'a'), ('2', 'b'), ('2', 'c')]