[Tutor] Question related to for loops

Manprit Singh manpritsinghece at gmail.com
Fri Mar 19 11:55:35 EDT 2021


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?


More information about the Tutor mailing list