Python sum() Built in Function

The sum() function in Python is a built-in function that returns the sum of an iterable such as a list, tuple, set or dictionary. It can also take an optional start parameter that specifies the initial value to be added to the sum.

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

# Example 1: Summing a list of numbers
num = [3.5, 5, 2, -5]

# start parameter is not provided
numSum = sum(num)
print(numSum)
# Output: 5.5

# start = 15
numSum = sum(num, 15)
print(numSum)
# Output: 20.5

# Example 2: Summing two numbers using +
a = 10
b = 20
c = a + b
# same as sum([a,b])
print(c) # Output: 30

# Example 3: Summing values of a dictionary
d = {'a':10, 'b':20, 'c':30}
dSum = sum(d.values())
print(dSum)
# Output: 60

# Note: sum(d.keys()) will raise an error as keys are not numbers

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions