In this tutorial, we will delve into one of Python’s built-in functions – the
sum() function. This function is a simple yet powerful tool for adding up numbers in an iterable like a list or tuple.
Basic Usage of sum()
The basic syntax of the
sum() function is as follows:
The ‘iterable’ can be a list, tuple etc., while the optional ‘start’ parameter specifies a value to be added to the result.
numbers = [1, 2, 3, 4] print(sum(numbers)) # Output: 10
Addition with Start Parameter
If you want to add a specific number to your total sum, you can use the ‘start’ parameter. Here’s how:
numbers = [1, 2, 3] print(sum(numbers, 10)) # Output: 16
In this example, Python adds up all numbers in the list and then adds 10 to it.
Error Handling with sum()
If you try using
sum() on non-numeric data types without providing an initial value for ‘start’, Python will throw an error. For instance:
data = ['a', 'b', 'c'] print(sum(data)) # TypeError: unsupported operand type(s) for +: 'int' and 'str'
To avoid such errors, you can use a generator expression to ensure that the
sum() function only operates on numeric values. Here’s an example:
data = ['a', 1, 'b', 2, 'c', 3] total = sum(i for i in data if type(i) == int) print(total) # Output: 6
sum() function is a versatile tool that can help you add up numbers in an iterable efficiently. Remember to handle non-numeric data types properly to avoid errors.
We hope this tutorial has been helpful in understanding how to use the Python
sum() function effectively!