Python sum() function with list parameter

前端 未结 3 754
栀梦
栀梦 2021-01-01 19:26

I am required to use the sum() function in order to sum the values in a list. Please note that this is DISTINCT from using a for loop to add the nu

相关标签:
3条回答
  • 2021-01-01 20:05

    Have you used the variable sum anywhere else? That would explain it.

    >>> sum = 1
    >>> numbers = [1, 2, 3]
    >>> numsum = (sum(numbers))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'int' object is not callable
    

    The name sum doesn't point to the function anymore now, it points to an integer.

    Solution: Don't call your variable sum, call it total or something similar.

    0 讨论(0)
  • 2021-01-01 20:14

    In the last answer, you don't need to make a list from numbers; it is already a list:

    numbers = [1, 2, 3]
    numsum = sum(numbers)
    print(numsum)
    
    0 讨论(0)
  • 2021-01-01 20:18
    numbers = [1, 2, 3]
    numsum = sum(list(numbers))
    print(numsum)
    

    This would work, if your are trying to Sum up a list.

    0 讨论(0)
提交回复
热议问题