2 views
in Python

Let's say I have numbers from [1,2,3,4,5...], and If I need to find (1+2)/2 and for a second, (2+3)/2 and then for the third, (3+4)/2, and so on, I don't know how to do that

Then, how to sum the entire list of numbers?

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

I also tried

b = sum(a)

print b

by (26.4k points)

We make two lists: one of each component aside from the first, and one of each component aside from the last. At that point,  we need is the average of each pair taken from the two records. We use zip to take sets from two lists.

I expect you need to see decimals in the outcome, despite the fact that your info esteems are whole numbers. As a matter of course, Python does integer division: it disposes of the remainder. To isolate things through as far as possible, we need to utilize skimming point numbers. Luckily, isolating an int by a float will deliver a float, so we simply utilize 2.0 for our divisor rather than 2.

so,

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

For question 2:

Try following code,

a = range(10)

# [0,1,2,3,4,5,6,7,8,9]

b = sum(a)

print b

# Prints 45

Want to learn python on detail? Join the python course fast!