Python built-in Method - sum()

h‮ptt‬s://www.theitroad.com

The sum() method is a built-in function in Python that is used to return the sum of all the elements in an iterable. An iterable is any object that can be looped over, such as a list, tuple, or set.

Here is the syntax for the sum() method:

sum(iterable, start=0)

The iterable parameter is the object that you want to sum up. The start parameter is an optional parameter that specifies the starting value for the sum. The default value is 0.

Here are some examples of using the sum() method:

x = [1, 2, 3, 4, 5]
s = sum(x)
print(s)    # output: 15

y = (6, 7, 8, 9, 10)
t = sum(y)
print(t)    # output: 40

In the first example, we create a list x containing the integers 1 to 5, and then use the sum() method to compute the sum of all the elements in the list. In the second example, we create a tuple y containing the integers 6 to 10, and then use the sum() method to compute the sum of all the elements in the tuple.

The sum() method is a convenient way to compute the sum of all the elements in an iterable, without having to write a loop to add up the elements one by one.