23maverick23
2/8/2013 - 10:58 PM

Python: Combine two lists

Python: Combine two lists

#!/usr/bin/env python

def combine_list(list1, list2, short=False):
    """
    Accepts 2 lists and returns a combined list mapping
    all values in list1 to values in list2. None values
    are replaced with an empty string.

    list1, list2: valid list objects
    short: True or False; stop at shortest list, else longest
    
    """
    list3 = []
    if short:
        from itertools import izip
        for a, b in izip(list1, list2):
            a = a if a is not None else ""
            b = b if b is not None else ""
            list3.append((a, b))
    else:
        from itertools import izip_longest
        for a, b in izip_longest(list1, list2):
            a = a if a is not None else ""
            b = b if b is not None else ""
            list3.append((a, b))
    return list3