Manash
Manash

Reputation: 41

How to fix sum() missing 1 required positional argument: 'y'?

Example code

a = [1,2,3]
print(sum(a))

Error traceback shown

Traceback (most recent call last)
<ipython-input-15-8c9e0f297c95> in <module>
      1 a = [1,2,3]
----> 2 print(sum(a))

TypeError: sum() missing 1 required positional argument: 'y'

Upvotes: 1

Views: 4057

Answers (2)

Ashwin Kadu
Ashwin Kadu

Reputation: 1

import builtins 

def sum_all(*args):
    return builtins.sum(args) 

sum_all(1,2,3,4)

I was also doing same mistake while defining a function and using sum function and it kept giving me TypeError, so I imported bulitins and passed *args as parameter and got the sum.

Upvotes: -1

Ryan M
Ryan M

Reputation: 20119

You've defined your own sum method that takes different parameters. For example, if I run this cell:

def sum(x, y):
    return x + y

followed by a cell with your code:

a = [1,2,3]
print(sum(a))

I get the same error output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-8c9e0f297c95> in <module>
      1 a = [1,2,3]
----> 2 print(sum(a))

TypeError: sum() missing 1 required positional argument: 'y'

To fix this, you can either rename your sum function to something else (such as my_sum), then go to the Kernel menu and click Restart, or use builtins.sum as suggested by Mike67 in the comments:

import builtins
a = [1,2,3]
builtins.sum(a)

I would recommend renaming the function to avoid the conflict, as you may run into other conflicts later. It's generally a good practice to avoid defining anything with the same name as a built-in function.

Upvotes: 2

Related Questions