Python double/nested for loop list comprehension

List comprehension for nested or double for loops with conditions

·

2 min read

Single for-loop with if condition

``````my_list = []
for x in range(3):
if x % 2 == 0:
my_list.append(x)
``````

In List comprehension

``````>>> my_list = [x for x in range(3) if x % 2 == 0]
>>> my_list
[0, 2]
``````

Single for-loop with if-else conditions

``````my_list = []
for x in range(3):
if x % 2 == 0:
my_list.append(y)
else:
my_list.append('odd')
``````

In List comprehension

``````>>> my_list = [x if x % 2 == 0 else 'odd' for x in range(3)]
>>> my_list
[0, 'odd', 2]
``````

Double for-loops with if condition

``````my_list = []
for x in range(3):
for y in range(x):
if y % 2 == 0:
my_list.append(y)
``````

In List comprehension

``````>>> my_list = [y for x in range(3) for y in range(x) if y % 2 == 0]
>>> my_list
[0, 0]
``````

See how the outer for loop came first then the inner for loop

Double for-loops with if and else conditions

``````my_list = []
for x in range(3):
for y in range(x):
if y % 2 == 0:
my_list.append(y)
else:
my_list.append('odd')
``````

In List comprehension

``````>>> my_list = [y if y % 2 == 0 else 'odd' for x in range(3) for y in range(x)]
>>> my_list
[0, 0, 'odd']
``````

Disclaimer: Writing double for loops with if-else conditions severely affects the readability of the code. Please use it at your own risk.

Did you find this article valuable?

Support Soumendra kumar sahoo by becoming a sponsor. Any amount is appreciated!