Search code examples
pythonpython-itertoolschain

Python itertools chain: possible to fill the shorter iterable with None


When using the itertools.chain method to flatten a list like:

list(itertools.chain(*zip(itr1,itr2)))

Is it possible to fill the shorter iterable with None like in itertools.imap for example? So I won't end up with:

In [1]: a = [1]
In [2]: b=[]

In [3]: list(itertools.chain(*zip(a,b))) 
Out[3]: []

Solution

  • Use itertools.izip_longest, pass the default value to the fillvalue parameter.

    Demo:

    In [1]: from itertools import chain, izip_longest
    
    In [2]: a = [1]
    
    In [3]: b = []
    
    In [5]: list(chain(*izip_longest(a, b, fillvalue='foo')))
    Out[5]: [1, 'foo']
    

    Default value of fillvalue is None.