1
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?

0

2 Answers 2

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

Use a list comprehension with two for clauses.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I think this is far one-line of code can go. But [x for x in [f1(i), f2(i)] for i in np.arange(3)] also works. That means the for order is optional?
The loop order matters. What you wrote does something entirely different, and probably not what you want.
0

I could do something like this:

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

But is there any better way?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.