I want to generate a list in python as follows -
[1, 1, 2, 4, 3, 9, 4, 16, 5, 25 .....]
You would have figured out, it is nothing but n,
List comprehensions generate one element at a time. Your options are, instead, to change your loop to only generate one value at a time:
[(i//2)**2 if i % 2 else i//2 for i in range(2, 20)]
or to produce tuples then flatten the list using itertools.chain.from_iterable()
:
from itertools import chain
list(chain.from_iterable((i, i*i) for i in range(1, 10)))
Output:
>>> [(i//2)**2 if i % 2 else i//2 for i in range(2, 20)]
[1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81]
>>> list(chain.from_iterable((i, i*i) for i in range(1, 10)))
[1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81]