Sum Function In Python

In this tutorial, I will teach you about the built-in sum function in python. So let’s start by discussing its definition.

Sum Function Definition :

Python built-in sum() function takes an iterable as an argument and returns the sum of all elements inside it. it also accepts a ‘start’ argument and adds it to the sum total.

Syntax :

sum(iterable,start = 0)

Sum Function In Python Examples :

Now let’s look at some examples :

Apply Sum To List

In the following code example, we will create a list of integers and apply sum function to it.

# Apply sum to list 
nums = [1,2,3,4,6,7]

print(sum(nums))

Save and run the above code you should see the following output.

sum function in python code example 1 output

One point to note is that iterable of sum function should only contain integers otherwise it will throw an error. Let’s look at the example.

print(sum(['a',2,3,4,5,6])) # It will Throw Error
print(sum(['1','2','3'])) # It will Also Throw Error

Apply Sum To Tuple

Let’s apply sum function in python to the builtin tuple.

nums = (1,2,3,4,5)

print(sum(nums))

The behavior of sum is the same to both tuple and list.

Output :

15

Apply Sum To Dictionary

The behavior of the sum function is slightly different to the dictionary data structure. In the case of a dictionary, it returns the sum of all keys. Let’s look at the example.

d = {1:"w",
     2:"a",
     3:"b"}

print(sum(d))

Safe and run the above code. you should see all keys of the dictionary summed up and printed on the console.

6

Apply Sum To Strings

Unfortunately, We can’t apply sum to the strings. Instead, we can sum the strings using the join method. here is the example.

# sum(['a','b']) : Error

#Instead use join
print(''.join(['a','b']))

Output :

'ab'

‘Start’ Argument In Sum

As discussed in the Introduction, the sum() function also accepts a ‘start’ keyword argument with a default value of 0. It simply adds that the start value to the sum total. Let’s look at an example.

nums = [1,2]

# Without Start
print(sum(nums))

# with start 
print(sum(nums,start = 10))

Output :

3
13

Explanation :

  • In the first case (without start argument) it simply sums the list i.e 1+2 = 3 and prints on the console.
  • In second case (with start = 10). along with a total of 3., it also adds the value of start argument. i.e 3 + 10 = 13

That’s wrap of the tutorial!

Also read about map function in python

Leave a Reply