Selene
Selene

Reputation: 37

python mutating a list while for loop Error

All I want to do is removing any duplicate elements in the list L.C(L) is working, but D(L) shows TypeError: argument of type 'NoneType' is not iterable when I run it. I think there no differences between these two functions. I can not figure out why it comes out with type error:

def C(L):
    l = []
    for i in range(len(L)):
        if not(L[i] in l):
            l = l + [L[i]]
    return l
def D(L):
    l = []
    print type(l)
    for i in range(len(L)):
        if not (L[i] in l):
            l = l.append(L[i])
    return l

Thanks for your help.

Upvotes: 0

Views: 56

Answers (2)

Marcin
Marcin

Reputation: 238747

l = l.append(L[i]) this results in l being Non, because append works in place. So just change l = l.append(L[i]) into l.append(L[i]). This should help.

Upvotes: 0

wim
wim

Reputation: 363324

This:

l = l + [L[i]]

is not equivalent to this:

l = l.append(L[i])

The line above assigns to l the value return value of calling the append function, which is None.

You can just use instead:

l.append(L[i])

Upvotes: 3

Related Questions