Search code examples
pythonpython-3.xpython-itertools

Join 2 lists using zip_longest but removing groups with None


How do I remove those groups which have None in them? Is there another alternative to zip_longest?

str1 = ['-', '+']
str2 = ['a','b','c']

list(itertools.zip_longest(str1, str2))

Output:

[('-','a'), ('+','b'), (None,'c')]

Expected output:

[[-a], [+b]]

Solution

  • zip_longest() is there as an alternative to the regular built-in zip(), which will truncate to the shortest list you give as an argument:

    >>> str1 = ['-', '+']
    >>> str2 = ['a','b','c']
    >>> zipped = list(zip(str1, str2))
    >>> print(zipped)
    [('-', 'a'), ('+', 'b')]
    >>> # the following more closely resembles your desired output
    >>> condensed = [''.join(tup) for tup in zipped]
    >>> print(condensed)
    ['-a', '+b']
    

    Note that you can also give a keyword argument fillvalue to itertools.zip_longest() to make it fill with something besides None:

    >>> zipped_long = list(itertools.zip_longest(str1, str2, fillvalue='~'))
    >>> print(zipped_long)
    [('-', 'a'), ('+', 'b'), ('~', 'c')]