How do I add together integers in a list (sum a list of numbers) in python?
Question:
Suppose I have a list of integers like [2, 4, 7, 12, 3]
. How can I add all of the numbers together, to get 28
?
Answers:
This:
sum([2, 4, 7, 12, 3])
You use sum()
to add all the elements in a list.
So also:
x = [2, 4, 7, 12, 3]
sum(x)
you can try :
x = [2, 4, 7, 12, 3]
total = sum(x)
x = [2, 4, 7, 12, 3]
sum_of_all_numbers= sum(x)
or you can try this:
x = [2, 4, 7, 12, 3]
sum_of_all_numbers= reduce(lambda q,p: p+q, x)
Reduce is a way to perform a function cumulatively on every element of a list. It can perform any function, so if you define your own modulus function, it will repeatedly perform that function on each element of the list. In order to avoid defining an entire function for performing p+q, you can instead use a lambda function.
First Way:
my_list = [1,2,3,4,5]
list_sum = sum(list)
Second Way(less efficient):
my_list = [1,2,3,4,5]
list_sum = 0
for x in my_list:
list_sum += x
Suppose I have a list of integers like [2, 4, 7, 12, 3]
. How can I add all of the numbers together, to get 28
?
This:
sum([2, 4, 7, 12, 3])
You use sum()
to add all the elements in a list.
So also:
x = [2, 4, 7, 12, 3]
sum(x)
you can try :
x = [2, 4, 7, 12, 3]
total = sum(x)
x = [2, 4, 7, 12, 3]
sum_of_all_numbers= sum(x)
or you can try this:
x = [2, 4, 7, 12, 3]
sum_of_all_numbers= reduce(lambda q,p: p+q, x)
Reduce is a way to perform a function cumulatively on every element of a list. It can perform any function, so if you define your own modulus function, it will repeatedly perform that function on each element of the list. In order to avoid defining an entire function for performing p+q, you can instead use a lambda function.
First Way:
my_list = [1,2,3,4,5]
list_sum = sum(list)
Second Way(less efficient):
my_list = [1,2,3,4,5]
list_sum = 0
for x in my_list:
list_sum += x