0

If I have this list comprehension:

[list(range(0,x)) for x in [1, 2, 3]] 

I get

[[0], [0, 1], [0, 1, 2]]

But I would like to get:

[0, 0, 1, 0, 1, 2]

Noticed that the example above is just a minimal example.

I have read a lot of SO questions that explain how to flatten a list of lists but I have found nothing on how to avoid the creation of sublist inside the list comprehension.

user2390182
  • 72,016
  • 6
  • 67
  • 89
obchardon
  • 10,614
  • 1
  • 17
  • 33

1 Answers1

3

Use a nested comprehension à la:

[y for x in [1,2,3] for y in range(x)]
# [0, 0, 1, 0, 1, 2]

Or, if you are into utils and cryptic brevity:

from itertools import chain

[*chain(*map(range, [1, 2, 3]))]
# or, as the traditionalists would suggest:
# list(chain.from_iterable(map(range, [1, 2, 3])))
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Perfect, thank you, it was not clear for me that we don't have to respect the "right to left" order in a nested list comprehension. – obchardon Feb 10 '21 at 16:04
  • Yeah, the scope in a flat nested comprehension can be counter-intuitive at first. But it is exactly the order as you would have collecting the elements in nested loops. – user2390182 Feb 10 '21 at 16:06