0

How do I remove all 'sublists' from a list in Python 3 i.e turn a list containing other lists into one giant list?

For example say I have:

myList = [[1,2,3],[4,5,6],[7,8,9]]

How do I turn this into:

[1,2,3,4,5,6,7,8,9]?

Thanks.

martineau
  • 119,623
  • 25
  • 170
  • 301
Arihan Sharma
  • 133
  • 1
  • 13

1 Answers1

1

Use itertools.chain.from_iterable:

from itertools import chain

myList = [[1,2,3],[4,5,6],[7,8,9]]

print(list(chain.from_iterable(myList)))

This prints:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

without using .from_iterables you can just unpack the list.

print(list(chain(*myList))

This does the same thing

Jab
  • 26,853
  • 21
  • 75
  • 114