# How to Use Python Sum Function with Examples? ## Share: ## Introduction

Python sum function is an efficient tool to sum a list of numerical values. Adding numbers is a general and most essential operation in daily lives as well as in computation. While coding, we do have occasions where we have to find the sum of various numbers. In this tutorial we will learn how to perform a Python sum function to add different numbers in different ways.

The sum function works with both integers and float values. The function takes all numerals in an iterable to add them. Normally, this task is done over and over repeatedly, but with Python sum function, it is not that assiduous. So let’s start learning about what the sum() function is and how it solves the iterables.

## What are Iterables?

Python has four built-in data structures. Iterables are the collection of values in any of those data structures. They are:

### 01) Lists

A list is a collection of all types of items. It is heterogeneous. You can write values in square brackets and that forms the list.

Syntax: list() function

### 02) Tuples

Tuples are a collection of immutable items. Once defined, you cannot make any change. You can write values in round brackets separated by commas to form a tuple.

Syntax: tuple() function

### 03) Dictionary

Dictionary is a collection of key-element/key-value pairs. They are heterogenous and mutable.

Syntax:  {key1:value1, key2:value2; etc }

### 04) Sets

Sets are very similar to lists but only unique items will be in it. You can write values in curly brackets to form a set.

Syntax: set() function

Related Post: 5 Best Ways for Python Reverse String with Examples

## What is The Python Sum function?

Summation, as I said, is a common problem in programming. In standard arithmetics, it looks like this:

List of numbers: [1, 2, 3, 4, 5]

1 + 2 + 3 + 4 + 5 = 15

We can solve such functions by hand, but solving for n numbers of a list could be troublesome and full of errors. Python sum function helps with that.

Python Sum function is an inbuilt function used to find the sum of all the iterables in a given function. The iterables can be a list, tuple, dictionary and sets. Sum() calculates the addition of both float point values and integers. For example – You can use the Python sum function to calculate the price of all the products purchased in the shop.

There can be an optional value to be added to the sum value of the iterable.

The syntax for the Python sum function is

sum(iterable, start)

The sum() function takes in two parameters:

• Iterable: The iterable objects you want to calculate. Can be a list, tuple, dictionary. Should be a float value or integer.
• Start: An optional value you want to add to the iterable value you’re calculating. If not given, it is presumed to be  0.

It presents two scenarios

1. If the start = 0. Then sum= sum(a). Where x = iterable value. It will only return the total of the list.
2. If start = Value. Then sum = (x, start). Where sum will then add x and start values and return the total addition.

How to use the sum function?

Let us take a look at the examples

### A Short Example for Python Sum Function in a List

`#listlist = [5,15,10]print(sum(list))`

Output:

`30`

That was a Python sum function without start value.

Now with start value:

`numbers = [5,10,15]# start parameter is not providedSum = sum(numbers)print(Sum)# start = 20Sum = sum(numbers, 20)print(Sum)`

Output:

`3040`

The Python sum function is used to find the sum but there is a limitation to it. The function throws an error if the values contain anything other than a number. Sometimes a list can contain multiple things, including letters, special symbols and numbers. If the python sum function is applied to such a list, the code will stop running and show an error.

### Python Sum Function Error Example

If there is any value except a number in the list, a TypeError will be raised.

`arr = ["a"] # start parameter is not providedSum = sum(arr)print(Sum) # start = 10Sum = sum(arr, 10)print(Sum)`

Output:

`Runtime Error :Traceback (most recent call last):  line 4, in     Sum = sum(arr)TypeError: unsupported operand type(s) for +: 'int' and 'str'`

## Python Sum For Loop

In using the Sum function Python for loop, the code first defines a list of numbers. Then it will initialize a variable called total to 0. Then the code iterates through the list using a for loop. The loop adds each number in the list to the total variable. And  the code prints the total value. The sum of numbers.

Let’s take an example of Python Sum for loop. We will use the Python sum function with a for loop to find the sum of n numbers.

First, we will take an integer data type as input and store it to a variable num. The sum() is 0 initially. We imply for loop to iterate the values. The range will start from 1 and increment num +1 till the list is completed. With each iteration, it will add the previous values and at last, print the sum of total value.

Related Post: 8 Best Methods To Use Python Filter List

### Sum Function Python For Loop Example:

`# Sum of numbers up to numinput = [1,2,3,4,5]num = int(input)   #We add one lower value because code iterates to +1sum = 0for value in range(1, num + 1):    sum = sum + valueprint(sum)`

Output 1:  For total 5 values, the sum is

`15`

Output 2:  For first 3 values-

`# Sum of numbers up to numinput = [1,2,3,4,5]num = int(input)     #We add one lower value because code iterates to +1sum = 0for value in range(1, num + 1):    sum = sum + valueprint(sum)`

Output: 6

## Python Sum Function With Recursion Function

Recursion is when a particular function is called. To sum numbers with recursion, we declare a function to add two values. It will return a value. Then we will call the function to add another value to the returned value.

You may also read about – How to Use Python Delete File?

### Python Sum Function with Recursion Example

`def total(numTotal):    theSum = 0    for i in numTotal:        theSum = theSum + i    return theSumprint(total([1,3,5,7,9]))`

Output:

`25`

## Python Sum List

Of Course you are not going to use the Python sum function for some meager calculations. What if there is a whole list of integer values, how will you find the sum of each element of that list?

We present to you two ways to compute it.

### 1. Python Sum For Loop

The most basic way is to use the Python Sum function and traverse the list using a for/while loop. Then add each value with each increment. You get the sum of the list at the end of the loop.

` def sum_of_list(l):  total = 0  for val in l:    total = total + val  return totalmy_list = [1,2,3,4,5]print(sum_of_list(my_list))`

Output

`15`

## Using Python Sum Function

This is the simplest approach. Using the Python Sum function will return the sum value with fewer lines of code.

`list = [1,2,3,4,5]print (sum(list))`

Output

`15`

## Python Sum Lambda

While computing a large or complex system, a useful way to solve it is break it down into simpler units and solve them. Then recombine the solved values. In Python sum function, we break down the problem into small lambda functions. With Python sum lambda, we can easily create separate functions for each different calculation.

For example, let’s say you are creating a calculator. One way to build its functions is to put every one of the operations (addition, subtraction, multiply and divide) inside one function- which can be complex and difficult to read. Another way is to separate each function and build them each a different python function. Create a different function for sum and subtraction and so on.

Lambda function eases coding by its concise syntax.

Look at the general function of the Python sum function below.

`def sum(x, y):	result = x + y	return result`

The above code takes too much space. We can reduce it to one line using lambda:

`sum = lambda a, b: a + b`

We have shown two approaches to use lambda to get the sum of all elements of a list:

### Python Sum Lambda to Sum 2 Elements

Adding 2 elements using the lambda function is pretty easy. The lambda takes in two parameters as input and returns the sum.
`x = lambda a, b: a+bsum = x(5, 8)print(sum)`
Output:
`13`

## .sum() Python Pandas DataFrame Method

One of the most important uses of Python is in data analysis. Python has an impressive set of data-centric packages. Pandas is one of those packages used to import and analyze data. Pandas dataframe.sum() function adds values in each column and returns the sum in column. You can specify the column axis as,

axis= ‘column’

The Python sum function then reads column-wise and returns a sum for each row. .sum() Python Pandas function also skips missing values in the dataframe during the sum calculations.

Syntax:

dataframe.sum(axis, skipna, level, numeric_only, min_count, kwargs)

Parameters:

axis: {index (0), columns (1)} Default Value: None

skipna: Exclude NA/null values during result computation. Default Value: None

level: If the axis is hierarchical, count to a particular level and collapse into a Series. Default Value: None

numeric_only: only int, float, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series. Default Value: None

min_count: The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA. Default Value: 0

### .sum() Python Pandas DataFrame Method Example

`import pandas as pddata = [[1, 5, 10], [2, 20, 40], [3, 15, 30]]df = pd.DataFrame(data)print(df.sum())`

Output

`0    61    402    80dtype: int64`

## Python Sum Array

Now, can you sum an array in Python? Let’s discuss how  to find the sum of elements in an array.

Let’s say we are given an array with the following values.

Arr = [1,2,3,4,5]

We need to print the sum of its elements. Let’s discuss two ways to do it.

### Method 1: Using Sum() function

In the Python sum function method, we will iterate through the array. Then add each array element to the sum variable and print the sum.

```# Python 3 code to find sum
# of elements in given array
def _sum(arr):

# initialize a variable
# to store the sum
# while iterating through
# the array later
sum = 0

# iterate through the array
# and add each element to the sum variable
# one at a time
for i in arr:
sum = sum + i
return(sum)
# driver function
arr = []
# input values to list
arr = [1, 2, 3, 4, 5]

# calculating length of array
n = len(arr)
ans = _sum(arr)

# display sum
print('Sum of the array is ', ans)
```
Output
`Sum of the array is  15`

### Method 2: Using For Loop

For this, we declare a variable to hold the value of sum(). Let’s say Sum= 0. Then run the for loop at a range and set a variable for sum. After iteration, print the value.

`arr = [1, 2, 3, 4, 5]Sum = 0for i in range(len(arr)):   Sum = Sum + arr[i]print (Sum)`

Output

`35`

## Conclusion

Python sum function is a powerful tool used to find the total of all the items in an iterable. The iterable should only contain whole numbers or decimal point numbers. In this tutorial we explored different ways to use the sum() function in Python. Now, we hope you have learned to use the function and can work with it on more complex programs.

2

## Share: ## Trusted By

Our platform focuses on making the remote hiring process easier by providing top quality vetted developers from around the world. Through our service many well-known companies have scaled their product development team.

## A Complete Guide on How to Hire Remote Angular Developers

Introduction Before hiring remote Angular developers, let us focus on knowing Angular. Angular is now one of the top…

## How To Hire Full Stack Developers: An Easy Guide to Find Full Stack Experts

In today’s competitive market, it is essential to hire Full Stack developers for your software development team. However, finding and hiring…

## A Complete Guide on QA Automation

Table of Contents With the rising complexity of modern software, human testers are finding it increasingly difficult to detect…