Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Sum Function in Python

Last Updated on June 21, 2024 by Abhishek Sharma

The sum function in Python is a built-in utility that simplifies the task of adding a sequence of numbers. Whether working with lists, tuples, or other iterable collections, sum provides a concise and efficient way to compute the total of numerical elements. This function is particularly useful in data processing, financial calculations, and any domain where aggregation of numerical data is required. Its versatility and ease of use make it a fundamental tool in the Python programming language, enabling developers to perform summation operations with minimal code.

What is Sum Function?

The sum function in Python is a powerful tool that is used for adding up the values that are present in an iterable object such as a list or a tuple. The sum function in Python can take a single iterable argument or two arguments if the second argument is used to provide a start value.

Syntax of Sum Function in Python

The syntax of the sum function in Python is relatively simple, and it is as follows:

sum(iterable[, start])

Here in the above syntax,

  • The "iterable" is the iterable object (such as a list, tuple, or set) for which we want to calculate the sum.
  • The "start" argument is an optional argument and is used to provide a start value for the sum. If the start argument is not provided, the default value of 0 is used.

Return Value of Sum Function in Python

The sum function in Python returns the sum of the values in the given iterable object. If the iterable contains integers, the result will be an integer, and if the iterable contains floating-point numbers, the result will be a floating-point number.

Time Complexity of Sum Function in Python

The time complexity of the sum function in Python is O(n) in the average case scenario, where "n" is the number of elements in the iterable object. This means that the time taken to calculate the sum increases linearly with the number of elements in the iterable.

Examples of Sum Function in Python

Now that we have acquired a basic knowledge of the syntax of the sum function in Python, let’s look at some examples to illustrate how it works.

Example 1 of Sum Function in Python: Sum of a List of Integers
The sum function in Python is used to calculate the sum of all integers present in a list. This has been implemented in the below code.

Code Implementation:

numbers = [1, 2, 3, 4, 5]
result = sum(numbers)
# Print the result
print(result)

Output

15

Explanation:
In this example, we define a list of integers and then use the sum function in Python to calculate the sum of the values in the list. The result is then printed to the console.

Example 2 of Sum Function in Python: Sum of a Tuple of Floating-Point Numbers
The code shows how we can calculate the sum of all floating numbers present in the list using the sum function in Python.

Code Implementation:

values = (3.14, 1.414, 2.718)
result = sum(values)
# Print the result
print(result)

Output

7.272

Explanation:
In this example, we define a tuple of floating-point numbers and then use the sum function in Python to calculate the sum of the values in the tuple. The result is then printed to the console.

Example 3 of Sum Function in Python: Summing a Subset of a List
We can use the sum Function in Python to find the sum of a subset of a list. The following code accomplishes this by using the slicing operator.

Code Implementation:

numbers = [1, 2, 3, 4, 5]
total = sum(numbers[:3])
print(total) 

Output

6

Explanation:
In this example, we have to sum only a subset of a list, we can use a slice. Here we make a variable name ‘total’, here we use slicing to get a list of the first three elements of a given list and if we observe on the output screen we get which is actually the sum of the first three elements of the list

Example 4 of Sum Function in Python: Summing a List of Tuples
We can also use the sum function in Python to calculate the sum of a list of tuples with the help of a for loop.

Code Implementation:

tuples = [(1, 2), (3, 4), (5, 6)]
total = sum(x[0] for x in tuples)
print(total)

Output

9

Explanation
In the above example, we have used the sum function in Python to sum the elements of a list of tuples. Here we simply iterate over on the tuple element and we simply pick the first element of the index and use the sum function to add up all the first elements of the tuple.

Example 5 of Sum Function in Python: Summing a List of Strings
Here is the code for summing up the list of strings

Code Implementation:

strings = ["1", "2", "3", "4", "5"]
total = sum(int(x) for x in strings)
print(total) 

Output

15

Explanation
In the above example, the list consists of strings that represent numbers in either integer or floating-point format. To calculate their sum, we can convert these strings to the respective data type and then use the sum function in Python to add all the elements of the list together. This involves converting the strings to integers before passing them to the sum function in Python, which allows us to easily compute their sum.

Example 6 of Sum Function in Python: Summing a List of Boolean Values
Here is another example showing the usage of the sum function in Python.

Code Implementation:

bools = [True, False, True, True, False]
total = sum(bools)
print(total)

Output:

3

Explanation
In the above example, we have a list name bools which has bool values, after this, we have to make the variable ‘total’ and use the sum function, here we got the 3 on output or console which means, the total true present is 3

Example 7 of Sum Function in Python: Summing a List of Objects with a Numeric Property
A list of objects that have a numeric property can also be summed by using the sum function in Python.

Code Implementation:

orders=[{"total": 10.99},{"total": 5.99},{"total": 7.99}]
total = sum(order["total"] for order in orders)
print(total) 

Output:

24.97

Explanation
If you have a list of objects that have a numeric property, you can use the sum function to sum the values of that property. Here we have a list of dictionaries representing sales orders with a total key and we use the sum function to sum the values of that property.
Note: The sum function in Python only works on iterables that contain numerical values, and it will raise a TypeError if it is called on an iterable that contains non-numeric values

Conclusion
The sum function in Python stands as an essential tool for aggregating numerical data within iterable collections. Its simplicity and efficiency allow developers to perform summation operations effortlessly, contributing to cleaner and more readable code. By understanding the capabilities and nuances of the sum function, programmers can enhance their data processing tasks, ensuring accurate and optimal performance in their applications. Whether dealing with simple lists or complex data structures, the sum function remains a reliable and powerful feature of Python.

Frequently Asked Questions(FAQs) related to Sum Function in Python

Here are some FAQs related to the sum function in Python

1. What is the sum function in Python?
Answer:
The sum function in Python is a built-in function that returns the sum of all the elements in an iterable, such as a list or tuple. It can also take an optional second argument to specify a starting value.

2. How do you use the sum function?
Answer:
You use the sum function by passing an iterable of numbers as the first argument. Optionally, you can provide a second argument as the starting value:

numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)  # Output: 15

# Using a starting value
total_with_start = sum(numbers, 10)
print(total_with_start)  # Output: 25

3. Can the sum function handle non-numeric data?
Answer:
No, the sum function is designed to work with numerical data. If the iterable contains non-numeric elements, it will raise a TypeError. All elements in the iterable must be numbers (integers or floats).

4. What is the default starting value for the sum function?
Answer:
The default starting value for the sum function is 0. This means if you don’t provide a second argument, the summation will start from zero.

5. What are the performance considerations when using the sum function?
Answer:
The sum function is efficient for summing elements in small to moderately sized iterables. However, for very large datasets, consider using other methods like numpy.sum from the NumPy library, which is optimized for performance with large arrays.

Leave a Reply

Your email address will not be published. Required fields are marked *