Why I need to add an extra parenthesis for sum() function?
Question:
if sum()
is a function in python, why does it need an extra parenthesis to work? Like other functions why sum()
is not working with single parenthesis?
It’s not working when it’s like this:
num1 = int(input())
num2 = int(input())
total = sum(num1, num2)
print(total)
It is working fine when I’m adding an extra parenthesis. Why this is happening?
total = sum((num1, num2))
Answers:
The sum
function in python takes in a tuple
or a list
of numbers as the first parameter ( because it should be iterable) and returns the sum of the elements.
sum ( num1, num2,...) #Gives Type Error since int is non iterable
sum ((num1,num2,...)) #works
sum([num1,num2,...] #works
in python, the sum() function takes as parameter an iterable, its actual function is tu sum the elements in a list, library or tuple. So, in your code what you are actually doing is creating a tuple with num1
& num2
in it and passing it as a parameter un the sum() function.
Python sum() is an inbuilt function that takes an iterable and returns the sum of items in it. The iterable may be Python list, tuple, set, or dictionary. The sum () function adds the elements of an iterable and returns the sum. Here you are passing a tuple with number values and pass the tuple as a parameter to sum() function, and in return, you will get the sum of tuple items.
if sum()
is a function in python, why does it need an extra parenthesis to work? Like other functions why sum()
is not working with single parenthesis?
It’s not working when it’s like this:
num1 = int(input())
num2 = int(input())
total = sum(num1, num2)
print(total)
It is working fine when I’m adding an extra parenthesis. Why this is happening?
total = sum((num1, num2))
The sum
function in python takes in a tuple
or a list
of numbers as the first parameter ( because it should be iterable) and returns the sum of the elements.
sum ( num1, num2,...) #Gives Type Error since int is non iterable
sum ((num1,num2,...)) #works
sum([num1,num2,...] #works
in python, the sum() function takes as parameter an iterable, its actual function is tu sum the elements in a list, library or tuple. So, in your code what you are actually doing is creating a tuple with num1
& num2
in it and passing it as a parameter un the sum() function.
Python sum() is an inbuilt function that takes an iterable and returns the sum of items in it. The iterable may be Python list, tuple, set, or dictionary. The sum () function adds the elements of an iterable and returns the sum. Here you are passing a tuple with number values and pass the tuple as a parameter to sum() function, and in return, you will get the sum of tuple items.