In Python, do you know double for loops with conditions in a list-comprehension?

Write a complex List Comprehension to show off your skills :D

Soumendra kumar sahoo
·Nov 25, 2020·

2 min read

In Python, do you know double for loops with conditions in a list-comprehension?

Subscribe to my newsletter and never miss my upcoming articles

Play this article

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]

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 affect the readability of the code. Please use at your own risk.

Photo by Lucas Benjamin on Unsplash

Did you find this article valuable?

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

See recent sponsors Learn more about Hashnode Sponsors
 
Share this