1

I attempted this list comprehension:

[sqrt(x), x**2 for x in range(rng)] 

but apparently this syntax doesn't work. I suppose I could do something like this:

[fn(x), fn(x) for x in range(rng) for fn in (sqrt(), lambda x: x**2)] 

but is there no cleaner way?

Edit: let's say rng is 3. I'd want an output of [0, 0, 1, 1, √2, 4]

2
  • Can you clarify what result you want? Commented May 16, 2019 at 23:29
  • "doesn't work" is not a problem specification. Touch the MCVE checkpoints, please: post both expected and actual results. Commented May 16, 2019 at 23:32

2 Answers 2

2

You have a few options:

[fx for x in range(rng) for fx in [sqrt(x), x**2]] 

or:

list(itertools.chain.from_iterable([sqrt(x), x**2] for x in range(rng))) 
Sign up to request clarification or add additional context in comments.

Comments

1

You can use double for-loop:

from math import sqrt rng = 3 print([item for x in range(rng) for item in (sqrt(x), x**2)]) # [0.0, 0, 1.0, 1, 1.4142135623730951, 4] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.