Search code examples
pythonalgorithmlistsum

Sum lists with different lengths


What's the best way to sum two or more lists even if they have different lengths?

For example I have:

lists = [[1, 2], [0, 3, 4], [5]]

and the result should be:

result = [6, 5, 4]

Solution

  • You can use itertools.izip_longest(), and use a fillvalue equal to 0

    In [6]: [sum(x) for x in itertools.izip_longest(*lists, fillvalue=0)]
    Out[6]: [6, 5, 4]
    

    for Python < 2.6:

    In [27]: ml = max(map(len, lists))
    
    In [28]: ml       #length of the longest list in lists
    Out[28]: 3
    
    In [29]: [sum(x) for x in zip(*map(lambda x:x+[0]*ml if len(x)<ml else x, lists))]
    Out[29]: [6, 5, 4]