Multiple Loops in List Comprehension in Python
Working with comprehension allows you to write multiple loops to generate a new list. The first specified loop will be the outer one, and the second specified loop will run inside it. This means the second loop will be nested within the first.
Let's form a list of tuples. For
this, first, we write two variables i
and j, enclosed in parentheses,
denoting a tuple. Then we start a loop
with the variable i, which should
generate the first number of 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)
Code execution result:
[(1, 1), (1, 2), (2, 1), (2, 2), (3, 1), (3, 2)]
Given two lists:
lst1 = ['1', '2']
lst2 = ['a', 'b', 'c']
Using comprehension, create a new list from them:
[('1', 'a'), ('1', 'b'), ('1', 'c'), ('2', 'a'), ('2', 'b'), ('2', 'c')]