Why do I get this error (NoneType)?
Question:
I know there are help forums on the NoneType
error. But for the love of me I can’t save my coding.
counter=0
agesList=[]
for line in database:
newlist=database[counter].split(',')
counter=counter+1
age=newlist[-2]
agesList=agesList.append(age)
#print(age)
print(agesList)
I have a document of comma separated values, and I split them all into their own list and take out the number I’m looking for which sits in the second to last positon of the newlist
. If I print age I get all of the correct ages 1 by 1 throughout the loop. But if I try to append all of the age numbers onto my blank list I get this error:
agesList=agesList.append(age)
AttributeError: 'NoneType' object has no attribute 'append'
Can I please get some help on why I get this error? Thanks
Answers:
You’re assigning a function call to your list which is why you’re overwriting your list.
Don’t do this:
agesList=agesList.append(age)
Simply do this:
agesList.append(age)
Instead of agesList=agesList.append(age)
use only agesList.append(age)
.
Because list.append()
returns None
and overrides your list.
Thus the first iteration of your for-loop will run fine, after that agesList
is None
and you will get the error you’re mentioning.
I know there are help forums on the NoneType
error. But for the love of me I can’t save my coding.
counter=0
agesList=[]
for line in database:
newlist=database[counter].split(',')
counter=counter+1
age=newlist[-2]
agesList=agesList.append(age)
#print(age)
print(agesList)
I have a document of comma separated values, and I split them all into their own list and take out the number I’m looking for which sits in the second to last positon of the newlist
. If I print age I get all of the correct ages 1 by 1 throughout the loop. But if I try to append all of the age numbers onto my blank list I get this error:
agesList=agesList.append(age)
AttributeError: 'NoneType' object has no attribute 'append'
Can I please get some help on why I get this error? Thanks
You’re assigning a function call to your list which is why you’re overwriting your list.
Don’t do this:
agesList=agesList.append(age)
Simply do this:
agesList.append(age)
Instead of agesList=agesList.append(age)
use only agesList.append(age)
.
Because list.append()
returns None
and overrides your list.
Thus the first iteration of your for-loop will run fine, after that agesList
is None
and you will get the error you’re mentioning.