[python] appending list but error 'NoneType' object has no attribute 'append'

I have a script in which I am extracting value for every user and adding that in a list but I am getting "'NoneType' object has no attribute 'append'". My code is like

last_list=[]
if p.last_name==None or p.last_name=="": 
    pass
last_list=last_list.append(p.last_name)
print last_list

I want to add last name in list. If its none then dont add it in list . Please help Note:p is the object that I am using to get info from my module which have all first_name ,last_name , age etc.... Please suggest ....Thanks in advance

This question is related to python list

The answer is


list is mutable

Change

last_list=last_list.append(p.last_name)

to

last_list.append(p.last_name)

will work


You are not supposed to assign it to any variable, when you append something in the list, it updates automatically. use only:-

last_list.append(p.last)

if you assign this to a variable "last_list" again, it will no more be a list (will become a none type variable since you haven't declared the type for that) and append will become invalid in the next run.


When doing pan_list.append(p.last) you're doing an inplace operation, that is an operation that modifies the object and returns nothing (i.e. None).

You should do something like this :

last_list=[]
if p.last_name==None or p.last_name=="": 
    pass
last_list.append(p.last)  # Here I modify the last_list, no affectation
print last_list

I think what you want is this:

last_list=[]
if p.last_name != None and p.last_name != "":
    last_list.append(p.last_name)
print last_list

Your current if statement:

if p.last_name == None or p.last_name == "":
    pass

Effectively never does anything. If p.last_name is none or the empty string, it does nothing inside the loop. If p.last_name is something else, the body of the if statement is skipped.

Also, it looks like your statement pan_list.append(p.last) is a typo, because I see neither pan_list nor p.last getting used anywhere else in the code you have posted.