You are here: Home / Topics / How to add all number in list in python

How to add all number in list in python

Filed under: Python on 2022-08-31 16:22:04

For calculating the sum of all numbers in the list in python, firstly we are aware of the list in python. list is mutable data type in python which hold a collection of items of different type.

example -
we have a list 
mylist=[1,2,3,4,5,6] 
and sum of all numbers in this list is :- 21 

program -

l=[1,2,3,4,5,6]
#first way
ans=0
for i in l:
ans=ans+i
print("sum of all number in list is - "+str(ans))

#second way
ans=sum(l)
print("Sum of all numbers in list is - "+str(ans))

Output-

sum of all number in list is - 21
Sum of all numbers in list is - 21

In this program, 
-In first way program use loop and take each number from list one by one add with the 'ans' and in last we print that ans 
-In Second way program use build-in function that is sum(), which calculate the addition of all number inside the list
-sum() function may also be used in other data type like set, tuple.


About Author:
Y
Yogesh     View Profile
I am Yogesh Sharma. I found this website very useful for all the students. It is a very good website for learning thousands of multiple choice questions. Basically it is like a community website. Everyone can add questions so am I. I will add mcqs in this website to help you.