Sum Function in Python

Last updated by Utkarsh Sahu on Dec 21, 2024 at 12:58 AM
Contents

In this article, we will be discussing the Python sum function and its application in

coding interviews. Python sum function is very helpful in coding interviews as it is easy to use and time-efficient. We’ll cover:

  • What Is the Sum Function in Python?
  • Sum Function Syntax
  • Find Average Using Python Sum Function
  • FAQs on Sum Function in Python

What Is the Sum Function in Python?

Sum function in Python is a built-in function that takes an iterable like a list, tuple, dictionary, or set as an argument, adds the elements of an iterable and returns the sum. We can also provide an optional start parameter which will be added to the sum of numbers in the iterable.

By default, the value of the start parameter is zero. In Python 3.8, the start argument is a keyword argument that can be defined in the sum function call itself or elsewhere in the code.

Syntax

sum(iterable, start)

The start parameter is optional, and its default value is zero. Therefore we can use the Python sum function in two possible ways:

Let ‘a’ be the name of our iterable.

  • Using the sum function as shown below will return the sum of the elements of a.

sum(a)

  • Using the sum functions shown below will return the sum of the elements of a + start.

sum(a, start)

Example

Let us see some examples of how to use the Python sum function.

Using Python Sum Function on a List

In the code below, we start with a list and use the Python sum function to calculate and print the sum of all the elements in our list.

a = [1, 2, 3, 5, 7, 11]

#using sum function without passing the start parameter

Sum = sum(a)
print(Sum)

#using sum function with start parameter

Sum = sum(a, 10)
print(Sum)

Output

29

39

Using Python Sum Function on a Tuple

In the code below, we will take a tuple and use the Python sum function to calculate and print the sum of all the elements in our tuple.

a = (3, 5 , 8, 13, 21)

#using sum function without the start parameter
Sum=sum(a)
print(Sum)

#using sum function with start parameter
Sum=sum(a, 11)
print(Sum)

Output

50

61

Using Python Sum Function on a Set

In the code below, we will take a set and use the Python sum function to calculate and

print the sum of all the elements in our set.

a = {1, 3, 5, 7, 9}

#using sum function without the start parameter
Sum=sum(a)
print(Sum)

#using sum function with start parameter
Sum=sum(a, 15)
print(Sum)

Output

25

40

Using Python Sum Function on a Dictionary

In the code below, we will take a dictionary and use the Python sum function to calculate and print the sum of all the keys in our dictionary.

a={
5: “Python”,
10: “sum”,
15: “function”
}

#using Python sum function without start parameter
Sum = sum(a)
print(Sum)

#using Python sum function with start parameter
Sum = sum(a, 20)
print(Sum)

Output

30

50

If, instead, you’d like to sum over all the values of a dictionary, then you’d need to explicitly pass them as .values() to the sum function as shown in the code below.

a={

   ‘a’ : 10,

   ‘b’ : 12,

   ‘c’ : 17

}

#using Python sum function without start parameter
Sum = sum(a.values())
print(Sum)

#using Python sum function with start parameter
Sum = sum(a.values(), 11)
print(Sum)

 Output

39

50

TypeError

You’ll get the TypeError when we use the Python sum function with an iterable consisting of data types other than numeric data types(int, float). Let’s see an example of TypeError in the Python sum function:

Example

a = [“interview”, “kickstart”, “Python”, “sum”]

Sum = sum(a)
print(Sum)

Output

Traceback (most recent call last):

  File “file.py”, line 2, in <module>

    print(sum(a))

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

Find Average using Python Sum Function

Let us solve a standard problem of finding the average using the Python sum function.

#find the average of numbers in the given list
a = [13, 47, 23, 55, 89]

Sum = sum(a)
Avg = Sum/len(a)

print(Avg)

Output

45

FAQs on Sum Function in Python

Question 1: Can we use the Python sum function to concatenate strings?

No, the Python sum function works only with numeric data types. To concatenate items of the given iterable (items must be strings), you may use the Python join() method.

Question 2: What will be the return value if we use the Python sum function with a dictionary?

If we use the Python sum function with a dictionary, the return value will be the sum of all the dictionary’s keys. Also, note that keys of the dictionary should be of a numeric data type; else, we will get TypeError.

Question 3: Can the Python sum function calculate the sum with exact precision?

No, if you need to add floating-point numbers with exact precision, then you should use math.fsum(iterable) instead.

import math

a = [1.1, 1.9, 2.1, 4.6]

# note that you cannot provide the start parameter when using fsum

Sum = math.fsum(a)
Avg = Sum/len(a)

print(Avg)

Output

2.425

Are You Ready to Nail Your Next Coding Interview?

Whether you’re a Coding Engineer gunning for Software Developer or Software Engineer roles, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!

If you’re looking for guidance and help with getting started, sign up for our free webinar. As pioneers in the field of technical interview prep, we have trained thousands of Software Engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

————

Article contributed by Anubhav Mishra

Last updated on: December 21, 2024
Author
Utkarsh Sahu
Director, Category Management @ Interview Kickstart || IIM Bangalore || NITW.
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Spring vs Spring Boot

Spring vs Spring Boot: Simplifying Java Application Development

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Product Marketing vs Product Management

Product Marketing vs Product Management

Java Scanner reset()

The upper() Function in Python

Insertion Sort Algorithm

Ready to Enroll?

Get your enrollment process started by registering for a Pre-enrollment Webinar with one of our Founders.

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC