[Tutor] Question related to for loops

Peter Otten __peter__ at web.de
Fri Mar 19 13:04:51 EDT 2021

```On 19/03/2021 16:55, Manprit Singh wrote:
> Dear sir ,
>
> consider a problem of finding sum of even and odd numbers inside a list..
> One can write a function like this :
>
> def odd_evensum(x):
>      odd, even = 0, 0
>      for i in x:
>          if i%2 != 0:
>              odd = odd + i
>          else:
>              even = even + i
>      return odd, even
>
> 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?

The first version because it is more likely to produce the correct output.

I would clean up it a bit though:

def odd_evensum3(x):
odd = 0
even = 0
for i in x:
if i % 2:
odd += i
else:
even += i
return odd, even

For bonus points: can you come up with an argument that would return

(4, 2)

for the first version of odd_evensum() and

(4, 0)

for the second?
```