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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With