Sum a list of numbers in Python

Question 1: So you want (element 0 + element 1) / 2, (element 1 + element 2) / 2, ... etc.

We make two lists: one of every element except the first, and one of every element except the last. Then the averages we want are the averages of each pair taken from the two lists. We use zip to take pairs from two lists.

I assume you want to see decimals in the result, even though your input values are integers. By default, Python does integer division: it discards the remainder. To divide things through all the way, we need to use floating-point numbers. Fortunately, dividing an int by a float will produce a float, so we just use 2.0 for our divisor instead of 2.

Thus:

averages = [(x + y) / 2.0 for (x, y) in zip(my_list[:-1], my_list[1:])]

Question 2:

That use of sum should work fine. The following works:

a = range(10)
# [0,1,2,3,4,5,6,7,8,9]
b = sum(a)
print b
# Prints 45

Also, you don't need to assign everything to a variable at every step along the way. print sum(a) works just fine.

You will have to be more specific about exactly what you wrote and how it isn't working.


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)

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)

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