How to create a list using if ... else in python ?

Published: February 05, 2019

DMCA.com Protection Status

To create a list in python, a solution is to use list comprehension, example:

>>> l = [i for i in range(10)]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Now, it is also possible to add a if ... else condition:

>>> l = [-1 if i < 5 else 1 for i in range(10)]
>>> l
[-1, -1, -1, -1, -1, 1, 1, 1, 1, 1]

References