0

For example, I have a list like this:

list_of_ranges = [range(0,5),range(10,100),range(500,777),range(1337,9001)]

My goal is to have a flattened list that combines all of the range functions. So it should look like this in the end:

[0,1,2,3,4,10,11,12,...,8999,9000]
Corey Levinson
  • 1,553
  • 17
  • 25

1 Answers1

0

You need to use itertools.chain and unpack your list using the * character to make this work. Just do:

from itertools import chain
list_of_ranges = [range(0,5),range(10,100),range(500,777),range(1337,9001)]
list(chain(*list_of_ranges))

Output:

[0,
 1,
 2,
 3,
 4,
 10,
 11,
 12,
 13,
 14,
...

You can read more about it here: https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists

Corey Levinson
  • 1,553
  • 17
  • 25
  • 1
    The `*` operator does _not_ dereference. [It unpacks the list](https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists). – jkr Aug 15 '20 at 02:39
  • Thx, I edited it to include the link. I had a hard time finding answers to this because it was not a list of lists, but a list of ranges, and ranges aren't lists...But it turns out the solution is exactly the same – Corey Levinson Aug 15 '20 at 02:52