Python ProgrammingPython Programming

Python list comprehension if else

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

test = [0, 1, 2, 3, 4, 5, 6]
thelist = [v * 10 if v < 3 else v * 2 for v in test if v != 3]
print(thelist)
[0, 10, 20, 8, 10, 12]