xxxxxxxxxx
a = [2, 4, 56, 7]
print(a[0] + a[1] + a[2] + a[3])
print(sum(a))
xxxxxxxxxx
"""If the numbers inside a list are all integers,
floats, or a combination of both, you can use the sum() function.
"""
number_list=[1, 2, 3, 4, 5, 7, 8, 5.5, 7.987, 7845.12454, 100, 200, 300]
print(sum(number_list))
# Now that I have helped you, don't you want to like this post?
xxxxxxxxxx
# Python code to demonstrate the working of
# sum()
numbers = [1,2,3,4,5,1,4,5]
# start parameter is not provided
Sum = sum(numbers)
print(Sum) # result is 25
# start = 10
Sum = sum(numbers, 10)
print(Sum) # result is 10 +25 = 35
xxxxxxxxxx
# Sum the contents of a list without the builtin sum function
list = [1,2,3,4,5]
sum = 0
# loop through each position of the list and
# add the contents of each position to the variable, sum
for i in range(len(list)):
sum += list[i]
# result is 1 + 2 + 3 + 4 + 5 = 15
print(sum)
xxxxxxxxxx
To get the sum of a list in python, you just call the built in sum() function.
An example:
>>> lst = [3, 7, 1, 9, 4]
>>> sum(lst)
24
xxxxxxxxxx
# Python code to demonstrate the working of
# sum()
numbers = [1,2,3,4,5,1,4,5]
# start parameter is not provided
Sum = sum(numbers)
print(Sum)
# start = 10
Sum = sum(numbers, 10)
print(Sum)
xxxxxxxxxx
# Python program to find sum of elements in list
total = 0
# creating a list
list1 = [11, 5, 17, 18, 23]
# Iterate each element in list
# and add them in variable total
for ele in range(0, len(list1)):
total = total + list1[ele]
# printing total value
print("Sum of all elements in given list: ", total)