Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (12.7k points)

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

But it's not working for me. Anyone, please help me!!

1 Answer

0 votes
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!

Related questions

0 votes
1 answer
asked Jul 16, 2019 in Python by leealex956 (7.3k points)
0 votes
1 answer
asked Feb 26, 2021 in Python by laddulakshana (12.7k points)
0 votes
1 answer

Browse Categories

...