[Tutor] Question related to for loops

Alan Gauld alan.gauld at yahoo.co.uk
Fri Mar 19 15:20:27 EDT 2021


On 19/03/2021 15:55, Manprit Singh wrote:

> In an other way if i write the same function like this :
> def odd_evensum(x):
>     odd = sum(i for i in x if i%2 != 0)
>     even = sum(i for i in x if i%2 == 0)
>     return odd, even
> 
> what should be preferred?

In this case you loop over the input list twice
 - once for odds and once for evens.
Then you loop over each of the resultant lists
again to do the summations.

I haven't measured it but would expect the second
version to be significantly slower for large input
lists.

-- 
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