python-3.xsum

How the sum() function works in python?


sum({'x':-10,'y':-20,'z':-30},60) 
#TypeError: unsupported operand type(s) for +: 'int' and 'str'

but

sum({-10: 'x', -20: 'y', -30: 'z'},60)  
#returns 0

Solution

  • As explained on Python's documentation, the sum function will sum the start value (2nd argument) with the items from an iterable data structure (1st argument). And, as mentioned on the comments, a dict by default is iterable over its keys.

    Thus, your second example is adding 60 (your start value) with your numerical dict items (keys):

    >>> 60 + (-10) + (-20) + (-30)

    0

    Your first example, however, is trying to add strings to numbers, which is not what sum() was intended to do:

    >>> 60 + 'x' + 'y' + 'z'

    (...) TypeError: unsupported operand type(s) for +: 'int' and 'str'

    If you want, for instance, to iterate a dict over its values you can use the values() function. For example:

    sum({'x':-10,'y':-20,'z':-30}.values(),60)