Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

join two lists by interleaving

Tags:

python

I have a list that I create by parsing some text. Let's say the list looks like

charlist = ['a', 'b', 'c']

I would like to take the following list

numlist = [3, 2, 1]

and join it together so that my combined list looks like

[['a', 3], ['b', 2], ['c', 1]]

is there a simple method for this?

like image 481
jml Avatar asked Dec 01 '22 08:12

jml


2 Answers

If you want a list of lists rather than a list of tuples you could use:

map(list,zip(charlist,numlist))
like image 107
JoshAdel Avatar answered Dec 22 '22 11:12

JoshAdel


The zip builtin function should do the trick.

Example from the docs:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
like image 37
Neil Aitken Avatar answered Dec 22 '22 09:12

Neil Aitken