Combine two lists into one multidimensional list

Question:

I would like to merge two lists into one 2d list.

list1=["Peter", "Mark", "John"]
list2=[1,2,3]

into

list3=[["Peter",1],["Mark",2],["John",3]]
Asked By: ogward

||

Answers:

list3 = [list(a) for a in zip(list1, list2)]
Answered By: eumiro

An alternative:

>>> map(list,zip(list1,list2))
[['Peter', 1], ['Mark', 2], ['John', 3]]

or in python3:

>>> list(map(list,zip(list1,list2)))
[['Peter', 1], ['Mark', 2], ['John', 3]]

(you can omit the outer list()-cast in most circumstances, though)

Answered By: ch3ka

I actually used:

list3a = np.concatenate((list1, list2))
list3 = np.reshape(list3a, (-1,2))

because otherwise I get the error: ‘list indices must be integers, not tuples’ when trying to reference the array.

Answered By: Andrew J Griffin

zip() iterates over both lists in sync and you will get a and b in parallel. Both values then create a new list as an element of the final list (list3).

list3 = [[a, b] for a, b in zip(list1, list2)]
Answered By: Alexey Berdnikov
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.