Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple separate lists into a list of lists

Tags:

python

list

Below are three lists which I would like to combine into a single nested list:

List_1=[1,2,3]
List_2=[4,5,6]
List_3=[7,8,9]

My attempt:

List_x=[]
List_x.append(List_1)
List_x.append(List_2)
List_x.append(List_3)
print List_x

Result:

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

Desired result: Same as the result I got, but the approach is extremely slow given the size of my actual data.

like image 725
Tiger1 Avatar asked Jan 24 '14 13:01

Tiger1


1 Answers

If you need a nested list (list of list), Concat them like this:

>>> l1 = [1,2,3]
>>> l2 = [4,5,6]
>>> l3 = [7,8,9]
>>> l123 = [l1,l2,l3]
>>> l123
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

If you want a flattened combined list, use itertools.chain:

>>> l1 = [1,2,3]
>>> l2 = [4,5,6]
>>> l3 = [7,8,9]
>>> from itertools import chain
>>> list(chain(*[l1,l2,l3]))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

If memory space is a problem, you can use append:

>>> l1 = [[1,2,3]]
>>> l1.append([4,5,6])
>>> l1.append([7,8,9])
>>> l1
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

If you want a flattened list and memory is a problem, use extend:

>>> l1 = [1,2,3]
>>> l1.extend([4,5,6])
>>> l1.extend([7,8,9])
>>> l1
[1, 2, 3, 4, 5, 6, 7, 8, 9]
like image 147
alvas Avatar answered Sep 28 '22 17:09

alvas