Sum Function Python

Sum Function Python – How to Use Sum() Function in Python

Aren’t you sure about Sum function Python? If yes, then this article will help you to a lot on how to use Sum() function in Python to get most out of it.

Sum Function Python

Python provides many inbuilt functions for doing frequent tasks to facilitate faster coding experience. One of them is to find the sum of the elements of an iterable.

It can be done using a user defined function, but it seems a hassle to write a function yourself. Moreover, when multiple types of iterables are involved, it becomes a tedious task to make separate functions for all of them. Luckily Python has an inbuilt function for this task. The sum() function in python returns the sum of all the elements of an iterable. 

What are Iterables ? 

Iterables are basically collections of data that can be used to store data efficiently. Before understanding the sum() function, one should know about the iterables in python.

There are 4 iterables pre-defined in python : ### 1. Lists Lists are collections of data values. They are index-based, meaning that the order of elements is preserved and we can access the elements with their index in the list.

They are also heterogenous meaning that we can create lists with multiple data type elements in the same list. Lists in python can be defined using the list() function or just enclosing all the values in box-brackets’[]’.

See also  What are The Uses Of R Programming Language in Different Industries

The list() function takes an iterable as parameter, meaning that one can give directly the list values as arguement or give an already defined iterable as arguement, whose values will be taken as the list values.

# list definition without list function
lis1 = [1, 2, 3, 4, 5]

# direct values
lis2 = list((6, 7, 8, 9, 10))

# from other list
lis3 = list(lis2)

2. Tuples

Tuples are also index-based, heterogenous collections of data like lists. They can be defined using tuple() function or enclosing values in parentheses’()’ The only difference between a tuple and a list is that a tuple is immutable(can not be modified) while a list is mutable(can be modified)

# list definition without list function
tup1 = (1, 2, 3, 4, 5)

# direct values
tup2 = tuple((6, 7, 8, 9, 10))

# from other tuple
tup3 = tuple(lis2)

3. Dictionaries

Dictionaries are a very useful data structure provided in python. A dictionary consists a collection of key-value pairs. It can be declared as key-value pairs in curly-brackets or using dictionary() function. Dictionaries are immutable like tuples and cannot contain elements with same keys i.e. duplicate keys are not allowed.

#using dictionary() function
dict1 = dictionary({1:”cherry”, 2:”tomato”, 3:”mango”})

#without dictionary() function
dict2 = {1:”cherry”, 2:”tomato”, 3:”mango”}

A dictionary differs from other iterables as its elements can be accessed through both index and keys. The key() and value() functions can be used to access the keys and associated values of a dictionary element respectively.

dict = {“fruit1″:”cherry”, “fruit2″:”tomato”, “fruit3″:”mango”}

# using index
a = dict[1].key()     # a contains 1
b = dict[1].value()   # b contains “tomato”

# using keys
c = dict[“fruit1”]    # c contains “cherry”

4. Sets

Sets in python are collections of data which are unordered meaning that we cannot access the elements of a set with index numbers. Moreover, sets are also immutable and do not allow duplicate values. Sets are used for quick removal of duplicate values and mathematical operations like Union etc. Sets can be defined using the set() function or the curly-brackets’{}’

#using set() function
set1 = set({“cherry”, “tomato”, “mango”})

#without set() function
set2 = {“cherry”, “tomato”, “mango”}

See also  How to Calculate Absolute Value in C++? 4 Best Methods

You May Also Like

10 Top Python Simple Projects Ideas For Beginners in 2023

Syntax for Sum Function Python

The sum() function in python can be used with the following syntax: sum(iterable, start) This syntax returns the sum of all the values of the iterable and the start parameter. The value of start paramater is taken to be if no arguement is passed. ### sum() for list

#for list
lis1 = [1, 2, 3, 4, 5]

print(“sum for list : “)
print(sum(lis1))

print(“sum for list with start 5: “)
print(sum(lis1, 5))

Output

sum for list :
15
sum for list with start 5:
20

Sum() for Tuple

#for tuple
tup1 = (1, 2, 3, 4, 5)

print(“sum for tuple : “)
print(sum(tup1))

print(“sum for tuple with start 5: “)
print(sum(tup1, 5))

Output

sum for tuple :
15
sum for tuple with start 5:
20

Sum() for Dictionary

#for dictionary
dict1 = {“a”:1, “b”:2, “c”:3, “d”:4, “e”:5}

print(“sum for dictionary : “)
print(sum(dict1))

print(“sum for dictionary with start 5: “)
print(sum(dict1.values(), 5))

Output

sum for dictionary :
15
sum for dictionary with start 5:
20

Sum() for Set

#for set
set1 = {1, 4, 3, 2, 5}


print(“sum for set : “)
print(sum(set1))

print(“sum for set with start 5: “)
print(sum(set1, 5))

Output

sum for set :
15
sum for set with start 5:
20

Where Can Sum Dunction Python be Used ?

sum function Python has many practical uses. Here is an example of Calculating the Average of the elements of a list

#Calculating average of list elements using sum()
numList = [1, 2, 3, 4, 5]
sum = sum(numList)
avg = sum/len(numList)
print(f”The Average of list items is : {avg}”)

See also  How Long Does it Take To Learn JavaScript For A Beginner?

Output

The Average of list items is : 3.0  

Exceptions

The Sum function Python works only with numeric values(int, float, complex). Else it throws an exception.

# A list with non-numeric element
lis = [1, 2, ‘a’, 4]
print(sum(lis))

OutputTraceback (most recent call last):
  File “<string>”, line 5, in <module>
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

Wrap Up

I hope this article would help you a lot to understand Sum function Python. In this article we have given all the crucial details on how to use Sum function Python. Therefore whenever you are trying to use Sum function in your Python code then you can also take the reference from this article.

Leave a Comment

Your email address will not be published. Required fields are marked *