Create a Python List with Multiple Elements per Iteration

def f1(x): return [(x+1)*2-1, (x+1)*2-1]
def f2(x): return [(x+1)*2, (x+1)*2]

[[f1(i), f2(i)] for i in np.arange(3)]

This is the code to generate a list of 3 list-pairs elements:

[[[1, 1], [2, 2]], [[3, 3], [4, 4]], [[5, 5], [6, 6]]]

However, I would like to obtain a list like below with one line of for loop.

[[1, 1], [2, 2], [3, 3], [4, 4], [5, 5], [6, 6]]

This is how it works with multi-lines:

n = []
for i in np.arange(3):
    n += [f1(i), f2(i)]

It’s like trying to compose 2 elements per time where I don’t know how to achieve += for one line of code. How can I do that?

Answer

[x for i in np.arange(3) for x in [f1(i), f2(i)]]

Use a list comprehension with two for clauses.

Leave a Reply

Your email address will not be published. Required fields are marked *