Advertisement
Advertisement


Sum a list of numbers in Python


Question

I have a list of numbers such as [1,2,3,4,5...], and I want to calculate (1+2)/2 and for the second, (2+3)/2 and the third, (3+4)/2, and so on. How can I do that?

I would like to sum the first number with the second and divide it by 2, then sum the second with the third and divide by 2, and so on.

Also, how can I sum a list of numbers?

a = [1, 2, 3, 4, 5, ...]

Is it:

b = sum(a)
print b

to get one number?

This doesn't work for me.

2018/06/02
1
377
6/2/2018 8:41:05 PM


Sum list of numbers:

sum(list_of_nums)

Calculating half of n and n - 1 (if I have the pattern correct), using a list comprehension:

[(x + (x - 1)) / 2 for x in list_of_nums]

Sum adjacent elements, e.g. ((1 + 2) / 2) + ((2 + 3) / 2) + ... using reduce and lambdas

reduce(lambda x, y: (x + y) / 2, list_of_nums)
2010/12/06

Question 2: To sum a list of integers:

a = [2, 3, 5, 8]
sum(a)
# 18
# or you can do:
sum(i for i in a)
# 18

If the list contains integers as strings:

a = ['5', '6']
# import Decimal: from decimal import Decimal
sum(Decimal(i) for i in a)
2016/12/09

You can try this way:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sm = sum(a[0:len(a)]) # Sum of 'a' from 0 index to 9 index. sum(a) == sum(a[0:len(a)]
print(sm) # Python 3
print sm  # Python 2
2018/06/02

>>> a = range(10)
>>> sum(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del sum
>>> sum(a)
45

It seems that sum has been defined in the code somewhere and overwrites the default function. So I deleted it and the problem was solved.

2018/06/02

Using a simple list-comprehension and the sum:

>> sum(i for i in range(x))/2. #if x = 10 the result will be 22.5
2018/04/18

Source: https://stackoverflow.com/questions/4362586
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]