Soumendra kumar sahoo
Soumendra's Blog

Follow

Soumendra's Blog

Follow

Python double/nested for loop list comprehension

List comprehension for nested or double for loops with conditions

Soumendra kumar sahoo's photo
Soumendra kumar sahoo
Β·Nov 25, 2020Β·

2 min read

Python double/nested for loop list comprehension

Photo by Γ–nder Γ–rtel on Unsplash

Play this article

Table of contents

  • Single for-loop with if condition
  • Single for-loop with if-else conditions
  • Double for-loops with if condition
  • Double for-loops with if and else conditions

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.

Β 
Share this