add all number in list in python by R4R Team

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.


Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!