Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add together integers in a list in python? [closed]

If I had a list like

x = [2, 4, 7, 12, 3]

What function/process would I use to add all of the numbers together?

Is there any way other than using sum ()?

like image 874
MaxwellBrahms Avatar asked Dec 17 '12 06:12

MaxwellBrahms


2 Answers

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.

like image 86
The Recruit Avatar answered Jan 29 '23 13:01

The Recruit


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)
like image 33
jackcogdill Avatar answered Jan 29 '23 14:01

jackcogdill