Welcome! In today’s tutorial, we are going to learn how to use the sum function in Python.
The sum function is a pre-built function in Python that is used for the addition of numbers in a list, tuple, array, etc. If you’re new to Python or just need a refresher, you’ve come to the right place. Let’s get started!
Step 1: Basic Usage of the Sum Function
In Python, the sum function takes two parameters: iterable elements and a start value (optional). The syntax is as follows:
1 |
sum(iterable, start) |
The iterable parameter is a sequence (list, tuple, etc.) or collection (set, dictionary, etc.) or an iterator object to be summed up. The start (optional) is added to the sum of numbers in the iterable.
For example:
1 2 |
numbers = [1, 2, 3, 4, 5] print(sum(numbers)) |
Step 2: Sum Function with the start Parameter
Now, let’s use the sum function with the start parameter. In this case, the start value will be added to the sum of numbers in the iterable.
For example:
1 2 |
numbers = [1, 2, 3, 4, 5] print(sum(numbers, 10)) |
Step 3: Summing Up Elements of Two Lists
You can also use the sum and zip functions together to sum up elements of two or more lists.
Here’s an example:
1 2 3 4 |
list1 = [1, 2, 3] list2 = [4, 5, 6] total = [sum(x) for x in zip(list1, list2)] print(total) |
The Full Code
1 2 3 4 5 6 7 8 9 10 |
numbers1 = [1, 2, 3, 4, 5] print(sum(numbers1)) numbers2 = [1, 2, 3, 4, 5] print(sum(numbers2, 10)) list1 = [1, 2, 3] list2 = [4, 5, 6] total = [sum(x) for x in zip(list1, list2)] print(total) |
Conclusion
To wrap up, the sum function is a simplistic yet incredibly useful feature within the Python language. With efficient comprehension, it can be extremely beneficial in realms like data analysis and manipulation, among other things.
We hope this tutorial was helpful in further expanding your Python knowledge.