Is there a way to apply izip_longest()
to lists inside a list?
If I have
somelist = [[1, 2, 3], "abcd", (4, 5, 6)]
is there a way to do
izip_longest(somelist[0], somelist[1], ....)
You can unpack the list, with the *
, like this
my_list = [[1, 2, 3], "abcd", (4, 5, 6)]
izip_longest(*my_list)
For example,
from itertools import izip_longest
my_list = [[1, 2, 3], "abcd", (4, 5, 6)]
print list(izip_longest(*my_list))
Output
[(1, 'a', 4), (2, 'b', 5), (3, 'c', 6), (None, 'd', None)]
Note: Using list
as a variable name will shadow the builtin list
function
If you choose to use a custom replacement value instead of None
, you can do it like this
print list(izip_longest(*my_list, fillvalue = -1))
Output
[(1, 'a', 4), (2, 'b', 5), (3, 'c', 6), (-1, 'd', -1)]