+2 votes
in Programming Languages by (77.2k points)
I have a list of lists like this:

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

and I want to convert this to a list like this:

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

What is the simple approach?

1 Answer

+1 vote
by (354k points)
selected by
 
Best answer

There are several ways to convert a list of lists to a list. You can use one of the following approaches:

>>> a = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
>>> sum(a,[])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> from functools import reduce
>>> reduce(lambda x,y: x+y,a)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> import operator
>>> reduce(operator.concat, a)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> import numpy as np
>>> np.concatenate(a)
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(np.concatenate(a))
[1, 2, 3, 4, 5, 6, 7, 8, 9]


...