In this tutorial, we will learn how to find the sum of a series in Python. Python, a versatile programming language, possesses several methods to calculate the sum of a series.
This can be done by using built-in functions, like sum() and reduce(), or by using loops, such as for and while. By the end of this tutorial, you will understand how to employ these methods to find the sum of a series in Python.
Step 1 – Using the sum() Function
The simplest way to calculate the sum of a series in Python is by using the built-in function sum(). This function calculates the sum of all the items in an iterable (like a list or a tuple), and optionally adds an extra value to the result.
Here is an example of using the sum() function to find the sum of a list of numbers.
1 2 3 |
numbers = [1, 2, 3, 4, 5] sum_numbers = sum(numbers) print(sum_numbers) |
The output would be 15.
Step 2 – Using the reduce() Function
Another way to find the sum of a series in Python is by using a function from the functools module, called reduce(). This function applies a binary function (in this case, an addition) to all the items in an iterable in cumulative way.
Here is an example of using the reduce() function to find the sum of a list of numbers.
1 2 3 4 5 6 7 |
from functools import reduce import operator numbers = [1, 2, 3, 4, 5] sum_numbers = reduce(operator.add, numbers) print(sum_numbers) |
For more details about the reduce() function, you can refer to the Python Documentation.
Step 3 – Using a Loop
If you want more control over the process, you can also create your own loop to find the sum of a series. Here is an example of a for loop to calculate the sum of a list of numbers.
1 2 3 4 5 |
numbers = [1, 2, 3, 4, 5] sum_numbers = 0 for n in numbers: sum_numbers += n print(sum_numbers) |
Displaying the Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# Using sum() function numbers = [1, 2, 3, 4, 5] sum_numbers = sum(numbers) print(sum_numbers) # Using reduce() function from functools import reduce numbers = [1, 2, 3, 4, 5] sum_numbers = reduce(lambda x, y: x + y, numbers) print(sum_numbers) # Using a for loop numbers = [1, 2, 3, 4, 5] sum_numbers = 0 for n in numbers: sum_numbers += n print(sum_numbers) |
Conclusion
There you have it! You can see that we utilized different techniques to find the sum of a series in Python. Importantly, you would generally use either the sum() function or the reduce() function from the functools module if you want to calculate the sum quickly and conveniently.
However, using loops can give you more flexibility and control over the computation process. Now you are ready to calculate the sum of a series in Python using different methods. Happy coding!