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?
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.
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