1

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.

1
  • 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. Commented Oct 5, 2017 at 5:15

4 Answers 4

7

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)

Sign up to request clarification or add additional context in comments.

Comments

2

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 Comment

although it is rather inconsistent, c is already defined in main
1

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]

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.