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
  • 112,593
  • 23
  • 157
  • 280
Arihan Sharma
  • 123
  • 1
  • 12

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
  • 25,138
  • 21
  • 72
  • 111