107

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

0

4 Answers 4

180

list is mutable

Change

last_list=last_list.append(p.last_name)

to

last_list.append(p.last_name)

will work

0
49

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
2
  • Oops. Actually its last_list=last_list.append(p.last_name)
    – learner
    Oct 15, 2012 at 11:54
  • so what would be my code to add last_name in list and skipping the none or blank last_name ?? Please suggest
    – learner
    Oct 15, 2012 at 12:01
15

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.

5

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.

1
  • so what would be my code to add last_name in list and skipping the none or blank last_name ?? Please suggest
    – learner
    Oct 15, 2012 at 12:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.