[Tutor] Question related to for loops
Alan Gauld
alan.gauld at yahoo.co.uk
Fri Mar 19 17:04:32 EDT 2021
On 19/03/2021 19:33, Mark Lawrence wrote:
>>> odd = sum(i for i in x if i%2 != 0)
>>> even = sum(i for i in x if i%2 == 0)
> I don't see any resultant lists to loop over, only a generator
> expression being passed to sum.
Good point, I was thinking the generator built a list then
summed it but with a generator it adds as it goes.
But it is still looping over the original list twice so
I'd still expect it to be slower. (Although 2 generators
in C might beat a single python loop) As always with
performance questions you'd need to measure it on real
world data.
--
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