[Tutor] Question related to for loops

Mark Lawrence breamoreboy at gmail.com
Fri Mar 19 15:33:31 EDT 2021


On 19/03/2021 19:20, Alan Gauld via Tutor wrote:
> 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 don't see any resultant lists to loop over, only a generator 
expression being passed to sum.

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


-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list