In Python, the sum() function is a built-in function used to find the sum of elements in an iterable such as a list, tuple, or set. It returns the sum of all elements in the iterable or a specified portion of it.
Syntax:
The syntax of the sum() function is as follows:
|
sum(iterable, start=0)
|
Here, iterable is the iterable that contains the elements to be summed, and start is the optional value that specifies the starting value of the sum. The default value of start is 0.
Examples:
Let's take a look at some examples of using the sum() function:
|
my_list = [1, 2, 3, 4, 5]
total = sum(my_list)
print(total)
|
Output:
15
In this example, we find the sum of all elements in the list my_list using the sum() function.
|
my_tuple = (1, 2, 3, 4, 5)
total = sum(my_tuple)
print(total)
|
Output:
15
In this example, we find the sum of all elements in the tuple my_tuple using the sum() function.
|
my_list = [1, 2, 3, 4, 5]
total = sum(my_list[2:4])
print(total)
|
Output:
7In this example, we find the sum of elements in the range [2:4] of the list my_list using the sum() function.
|
my_list = [1, 2, 3, 4, 5]
total = sum(my_list, 10)
print(total)
|
Output:
25
In this example, we find the sum of all elements in the list my_list starting from 10 using the sum() function.
Conclusion:
In conclusion, the sum() function is a useful built-in function in Python that can be used to find the sum of elements in an iterable. It is commonly used in mathematical and statistical calculations in Python.