pythonlisttuplesadditionmembers

Python Add Elements of a List (or Set, or whatever Data Type is appropriate)


Is there an easy way to add the members of two equally sized lists (or tuple or whatever data type would work best)?

I have, for example a and b with 2 elements:

a = (0, 10)
b = (0, -10)

I want to add them and get as result:

result = (0, 0)

NOT (0, 10, 0, -10)


Solution

  • You can do this in one line in Python:

    map(sum, zip(A, B))
    

    Example:

    >>> B = [1, 2, 3, 4]
    >>> C = [1, 2, 4, 8]
    >>> map(sum, zip(B, C))
    [2, 4, 7, 12]