1
votes

I run the following code:

import sys
def find_common(a,b,c):
    d=[]
    for i in a:
        if i in b:
            d=d.append(i)
    for i in d:
        if i not in c:
            c=c.append(i)
    print(c)
    return c

if __name__ == '__main__':
    a=[1,1,2,4]
    b=[2,2,3,4]
    c=[]
    find_common(a,b,c)
    sys.exit()

but get the following error:

d=d.append(i)  
AttributeError: 'NoneType' object has no attribute 'append' 

Why is it happening? Please help to fix it.

4
You have reassigned d with the return value of d.append, which is None, resulting in the error. You do not need to assign the return value of list.append to some variable. - metatoaster

4 Answers

4
votes

d.append(i) returns None
therefore:
d = d.append(i) assigns None to d

replace that line with:
d.append(i)

The same goes for c = c.append(i)

1
votes

first you don't need to reassign the d

d=d.append(sth)


import sys
def find_common(a,b,c):
    d=[]
    for i in a:
        if i in b:
            d=d.append(i)
    for i in d:
        if i not in c:
            c=c.append(i)
    print(c)
    return c

if __name__ == '__main__':
    a=[1,1,2,4]
    b=[2,2,3,4]
    c=[]
    find_common(a,b,c)
    sys.exit()
1
votes

I am not going to repeat what the others have already said when it comes to append() returning None, but I will suggest a shorter solution, which works with arbitrary number of arguments:

def find_common(*args):
    return list(set.intersection(*[set(arg) for arg in args]))

>>> a = [1, 3, 2, 4]
>>> b = [2, 2, 3, 4]
>>> c = [3, 3, 4, 5]
>>> d = [1, 4, 7, 6]
>>> find_common(a, b, c, d)
[4]
0
votes

Problem here is that you are reassigning d.append() to d.

d.append() returns None.

d = []
print d.append(4) #None

So change your code to following and it will work.

def find_common(a,b,c):
    d=[]
    for i in a:
        if i in b:
            d.append(i)
    for i in d:
        if i not in c:
            c.append(i)
    print(c)
    return c