Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two lists into a list of lists

Tags:

python

list

I have two lists:

a = ['1', '2']
b = ['11', '22', '33', '44']

And I to combine them to create a list like the one below:

op = [('1', '11'), ('2', '22'), ('', '33'), ('', '44')]

How could I achieve this?

like image 757
sam Avatar asked Feb 10 '23 08:02

sam


1 Answers

You want itertools.zip_longest with a fillvalue of an empty string:

a = ['1', '2']
b = ['11', '22', '33', '44']

from itertools import zip_longest # izip_longest for python2

print(list(zip_longest(a,b, fillvalue="")))
[('1', '11'), ('2', '22'), ('', '33'), ('', '44')]

For python2 it is izip_longest:

from itertools import izip_longest 

print(list(izip_longest(a,b, fillvalue="")))
[('1', '11'), ('2', '22'), ('', '33'), ('', '44')]

If you just want to use the values you can iterate over the the izip object:

for i,j  in izip_longest(a,b, fillvalue=""):
   # do whatever

Some timings vs using map:

In [51]: a = a * 10000

In [52]: b = b * 9000

In [53]: timeit list(izip_longest(a,b,fillvalue=""))
100 loops, best of 3: 1.91 ms per loop

In [54]: timeit [('', i[1]) if i[0] == None else i  for i in map(None, a, b)]
100 loops, best of 3: 6.98 ms per loop

map also creates another list using python2 so for large lists or if you have memory restrictions it is best avoided.

like image 93
Padraic Cunningham Avatar answered Feb 13 '23 04:02

Padraic Cunningham