Read Python Interview Questions and Answers for Beginners and Experienced

Python sum() function

In this post of Python tutorial for beginners, we will study another sum() function of Python built-in functions. we will study what is sum() function, why it is used, its syntax and few example of Python sum() function.

 

Introduction to Python sum() function

sum() function do the summation of all the elements which is passed through it. As its name suggests that it will sum the items which are passed in it.

 

Syntax of sum () function

 

sum(iterable,[start])

or

sum(iterable)

 

  • sum() is the function name.
  • iteratable is parameter to sum function, whose sum needs to be calculated.
  • Iterable could be numbers, list, tuple etc.
  • sum function do sum by taking items left to right.
  • sum function can only work with integer/numeric values.
  • start is the number which is added after summation of iterable items.
  • [start] is optional.

 

Example of sum() function


# Python sum() function example

print ("Sum is :",sum((1,2,3)))

 

Output

Sum is : 6
  • In above example 1,2,3 are numeric values, sum function do the summation of these 3 values.
  • In this example, we did not pass the [start] variable.

 


# Python sum() function example

print ("Sum is :",sum((1,2,3),10))

 

Output

Sum is : 16
  • In this example, we provide another parameter which has value 10.
  • sum value add the 6 to 10 and give final output as 10.

 

Sum function with list, tuple, set example


# Python sum() function example

tuple1=(10,20,30)

print("Sum of tuple1 is",sum(tuple1))

list1=[11,22,33]

print("Sum of list1 is",sum(list1))

salary={20000:"katty",
70000:"tonny",
30000:"Sussy"
}

print("Sum of Salary is",sum(salary))

 

Output

Sum of tuple1 is 60
Sum of list1 is 66
Sum of Salary is 120000

 

  • In the above example, we have Python list, Python tuple and Python set, on which we apply sum() function of Python.