appending list but error 'NoneType' object has no attribute 'append'

PythonList

Python Problem Overview


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

Python Solutions


Solution 1 - Python

list is mutable

Change

last_list=last_list.append(p.last_name)

to

last_list.append(p.last_name)

will work

Solution 2 - Python

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

Solution 3 - Python

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.

Solution 4 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlearnerView Question on Stackoverflow
Solution 1 - PythonjessiejcjsjzView Answer on Stackoverflow
Solution 2 - PythonCédric JulienView Answer on Stackoverflow
Solution 3 - PythonJayesh MishraView Answer on Stackoverflow
Solution 4 - PythonJoe DayView Answer on Stackoverflow