[Tutor] Confusion about name in the target list of for loop

Alan Gauld alan.gauld at yahoo.co.uk
Fri Aug 28 08:33:30 EDT 2020


On 28/08/2020 12:18, Manprit Singh wrote:
> Dear sir ,
> Consider a problem of finding the average of numbers(1,2, 3, 4, 5). if this
> is solved using the for loop in this way,  is it correct ?
> 
> s = 0
> for i in range(1, 6):
>     s = s + i
> print(s / i)
> 3.0

In that it will work yes it is correct.
However, it is far from the best approach.

> My question is, the way i have used variable in the target list, just after
> the completion of for loop, is its appropriate use or not.

Remember that 'i' will have the value of the last member of the
collection not the index. So...

It's only appropriate if dealing with a straight range of numbers. If
the numbers were in an unordered, non-sequential list it would break.
You could use the enumerate() function to get the index of the item -
that will work for any collection.

Better however is to use the sum() and len() functions:

ave = sum(collection)/len(collection)

No loops, no risk of boundary errors. Much more reliable.

There is also the Python "statistics" module in the standard
library which can deliver several variations on average:
mean, median, etc.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list