How can I convert List of lists to list in Python?

ipython
python

#1

Hi,

I have a variable having having data stored as list of lists (see below ), now I want to convert it into a single list. Please guide with techniques to perform it in python.

Variable1

[[2,3],[4,5,6],[8,9,10]],[[3,5,23,12],[23,56,78],[45,78,89,90]],[[2,3],[5,6],[7]]

Required Output:

[2,3,4,5,6,8,9,10],[3,5,23,12,23,56,78,45,78,89,90],[2,3,5,6,7]

Regards,
Imran


#2

@Imran

This should do the job:

a = [[1,2,3],[4,5,6],[7,8,9]],[[10,11],[12,13,14]]

# <codecell>

a

# <codecell>

new_list = []
final_list = []

# <codecell>

for i in a:
    for j in i:
        new_list = new_list + j
    final_list.append(new_list)
    new_list = []

# <codecell>

final_list

# <codecell>

#3

Or this.

>>> from itertools import chain
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
>>> list(chain.from_iterable(a))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

#4

or this

f = [[2,3],[4,5,6],[8,9,10]],[[3,5,23,12],[23,56,78],[45,78,89,90]],[[2,3],[5,6],[7]]

f
([[2, 3], [4, 5, 6], [8, 9, 10]], [[3, 5, 23, 12], [23, 56, 78], [45, 78, 89, 90]], [[2, 3], [5, 6], [7]])
q= map(lambda m : reduce(lambda x,y : x+y , m),f)

q
[[2, 3, 4, 5, 6, 8, 9, 10], [3, 5, 23, 12, 23, 56, 78, 45, 78, 89, 90], [2, 3, 5, 6, 7]]


#5

single line solution

num_list=[[2,3],[4,5,6],[8,9,10]]
b = [j for i in num_list for j in i]
print b
[2, 3, 4, 5, 6, 8, 9, 10]

The line basically tells python loop i in item_list and loop j in i(i will be having individual lists) then put j into b. This shorthand way of creating lists/iterating over lists in python is called List Comprehension.

You can follow this amazing tutorial https://www.analyticsvidhya.com/blog/2016/01/python-tutorial-list-comprehension-examples/ to learn more about this advanced python technique.