Python ProgrammingPython Programming

Python list comprehension multiple conditions

Example-1

thelist = [x for x in range(20) if x % 2 == 0]
print(thelist)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Example-2

thelist = [[x * 100, x][x % 2 != 0] for x in range(1, 11)]
print(thelist)
[1, 200, 3, 400, 5, 600, 7, 800, 9, 1000]

Example-3

thelist = [x ** x if x % 2 == 0 else 49 for x in range(1, 11)]
print(thelist)
[49, 4, 49, 256, 49, 46656, 49, 16777216, 49, 10000000000]