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
LBes
3,3661 gold badge32 silver badges66 bronze badges
asked Oct 15, 2012 at 11:35
0
list is mutable
Change
last_list=last_list.append(p.last_name)
to
last_list.append(p.last_name)
will work
Uma Madhavi
4,8715 gold badges38 silver badges73 bronze badges
answered Apr 29, 2017 at 7:18
jessiejcjsjzjessiejcjsjz
1,8011 gold badge9 silver badges3 bronze badges
0
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
answered Oct 15, 2012 at 11:52
Cédric JulienCédric Julien
78.6k15 gold badges127 silver badges132 bronze badges
2
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.
answered Jan 1, 2020 at 13:45
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.
answered Oct 15, 2012 at 11:56
Joe DayJoe Day
6,9654 gold badges25 silver badges26 bronze badges
1
If you attempt to call the append() method on a variable with a None value, you will raise the error AttributeError: ‘NoneType’ object has no attribute ‘append’. To solve this error, ensure you are not assigning the return value from append() to a variable. The Python append() method updates an existing list; it does not return a new list.
This tutorial will go through how to solve this error with code examples.
Table of contents
- AttributeError: ‘NoneType’ object has no attribute ‘append’
- Example
- Solution
- Summary
AttributeError: ‘NoneType’ object has no attribute ‘append’
AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The part “‘NoneType’ object has no attribute ‘append’” tells us that the NoneType object does not have the attribute append(). The append()
method belongs to the List data type, and appends elements to the end of a list.
A NoneType object indicates no value:
obj = None print(type(obj))
<class 'NoneType'>
Let’s look at the syntax of the append method:
list.append(element)
Parameters:
element
: Required. An element of any type to append.
The append method does not return a value, in other words, it returns None. If we assign the result of the append()
method to a variable, the variable will be a NoneType object.
Example
Let’s look at an example where we have a list of strings, and we want to append another string to the list. First, we will define the list:
# List of planets planets = ["Jupiter", "Mars", "Neptune", "Saturn"] planets = planets.append("Mercury") print(planets) planets = planets.append("Venus") print(f'Updated list of planets: {planets}')
Let’s run the code to see what happens:
None --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) 5 planets = planets.append("Mercury") 6 ----≻ 7 planets = planets.append("Venus") 8 9 print(f'Updated list of planets: {planets}') AttributeError: 'NoneType' object has no attribute 'append'
The error occurs because the first call to append returns a None value assigned to the planets variable. Then, we tried to call append() on the planets variable, which is no longer a list but a None value. The append() method updates an existing list; it does not create a new list.
Solution
We need to remove the assignment operation when calling the append() method to solve this error. Let’s look at the revised code:
# List of planets planets = ["Jupiter", "Mars", "Neptune", "Saturn"] planets.append("Mercury") planets.append("Venus") print(f'Updated list of planets: {planets}')
Let’s run the code to see the result:
Updated list of planets: ['Jupiter', 'Mars', 'Neptune', 'Saturn', 'Mercury', 'Venus']
We update the list of planets by calling the append() method twice. The updated list contains the two new values.
Summary
Congratulations on reading to the end of this tutorial! The error AttributeError: ‘NoneType’ object has no attribute ‘append’ occurs when you call the append() method on a NoneType object. This error commonly occurs if you call the append method and then assign the result to the same variable name as the original list. The append() method returns None, so you will replace the list with a None value by doing this.
For further reading on AttributeErrors, go to the article: How to Solve Python AttributeError: ‘numpy.ndarray’ object has no attribute ‘append’.
Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.
Have fun and happy researching!
When you’re working with lists in Python, you might get the following error:
AttributeError: 'NoneType' object has no attribute 'append'
This error occurs when you call the append()
method on a NoneType
object in Python.
This tutorial shows examples that cause this error and how to fix it.
1. calling the append()
method on a NoneType object
To show you how this error happens, suppose you try to call the append()
method on a NoneType
object as follows:
fruit_list = None
fruit_list.append("Apple")
In the above example, the fruit_list
variable is assigned the None
value, which is an instance of the NoneType
object.
When you call the append()
method on the object, the error gets raised:
Traceback (most recent call last):
File "main.py", line 3, in <module>
fruit_list.append("Apple")
AttributeError: 'NoneType' object has no attribute 'append'
To fix this error, you need to call the append()
method from a list object.
Assign an empty list []
to the fruit_list
variable as follows:
fruit_list = []
fruit_list.append("Apple")
print(fruit_list) # ['Apple']
This time, the code is valid and the error has been fixed.
2. Assigning append()
to the list variable
But suppose you’re not calling append()
on a NoneType
object. Let’s say you’re extracting a list of first names from a dictionary object as follows:
customers = [
{"first_name": "Lisa", "last_name": "Smith"},
{"first_name": "John", "last_name": "Doe"},
{"first_name": "Andy", "last_name": "Rock"},
]
first_names = []
for item in customers:
first_names = first_names.append(item['first_name'])
At first glance, this example looks valid because the append()
method is called on a list.
But instead, an error happens as follows:
Traceback (most recent call last):
File "main.py", line 11, in <module>
fruit_list = fruit_list.append(item['first_name'])
AttributeError: 'NoneType' object has no attribute 'append'
This is because the append()
method returns None
, so when you do an assignment inside the for
loop like this:
first_names = first_names.append(item['first_name'])
The first_names
variable becomes a None
object, causing the error on the next iteration of the for
loop.
You can verify this by printing the first_names
variable as follows:
for item in customers:
first_names = first_names.append(item['first_name'])
print(first_names)
The for
loop will run once before raising the error as follows:
None
Traceback (most recent call last):
As you can see, first_names
returns None
and then raises the error on the second iteration.
To resolve this error, you need to remove the assignment line and just call the append()
method:
customers = [
{"first_name": "Lisa", "last_name": "Smith"},
{"first_name": "John", "last_name": "Doe"},
{"first_name": "Andy", "last_name": "Rock"},
]
first_names = []
for item in customers:
first_names.append(item["first_name"])
print(first_names)
Output:
Notice that you receive no error this time.
Conclusion
The error “NoneType object has no attribute append” occurs when you try to call the append()
method from a NoneType
object. To resolve this error, make sure you’re not calling append()
from a NoneType
object.
Unlike the append()
method in other programming languages, the method in Python actually changes the original list object without returning anything.
Python implicitly returns None
when a method returns nothing, so that value gets assigned to the list if you assign the append()
result to a variable.
If you’re calling append()
inside a for
loop, you need to call the method without assigning the return value to the list.
Now you’ve learned how to resolve this error. Happy coding! 😃
Если вы программист, скорее всего, вы сталкивались с сообщением об ошибке «AttributeError: ‘NoneType’ объект не имеет атрибута ‘append’» в тот или иной момент. Это сообщение об ошибке может разочаровать, так как оно часто не дает вам много информации о том, почему это произошло. В этом посте мы более подробно рассмотрим, что вызывает эту ошибку и как ее можно исправить.
Понимание сообщения об ошибке
Прежде чем мы углубимся в причины сообщения об ошибке, давайте сначала рассмотрим, что оно на самом деле означает. Проще говоря, сообщение об ошибке сообщает вам, что вы пытаетесь вызвать append()
метод на объекте, который None
. В Питоне, None
— это специальный объект, представляющий отсутствие значения.
Объект, который None
не имеет никаких атрибутов, в том числе append()
. Когда вы пытаетесь позвонить append()
на None
объект, вы получаете сообщение об ошибке «AttributeError: объект NoneType не имеет атрибута« добавить »».
Распространенные причины ошибки
Теперь, когда мы знаем, что означает сообщение об ошибке, давайте рассмотрим некоторые распространенные причины этой ошибки:
1. Забыли присвоить значение переменной
Одной из частых причин сообщения об ошибке «AttributeError: объект NoneType не имеет атрибута« добавить »» является то, что вы забыли присвоить значение переменной перед попыткой ее использования.
Например, предположим, что у вас есть следующий код:
my_list = None
my_list.append(1)
Войти в полноэкранный режимВыйти из полноэкранного режима
В этом случае мы пытаемся вызвать append()
метод на my_list
но мы забыли присвоить значение my_list
. Это значит, что my_list
является None
и мы получаем сообщение об ошибке.
Чтобы исправить это, обязательно присвойте значение my_list
перед попыткой использовать его:
my_list = []
my_list.append(1)
Войти в полноэкранный режимВыйти из полноэкранного режима
2. Неправильная область видимости переменных
Другой распространенной причиной появления сообщения об ошибке «AttributeError: объект NoneType не имеет атрибута ‘append’» является неправильная область видимости переменной.
Например, предположим, что у вас есть следующий код:
def my_func():
my_list = None
my_list.append(1)
my_func()
Войти в полноэкранный режимВыйти из полноэкранного режима
В этом случае мы определяем my_list
внутри my_func()
функция. Однако, как только функция будет выполнена, my_list
выходит за рамки и устанавливается на None
. Когда мы пытаемся позвонить append()
на my_list
получаем сообщение об ошибке.
Чтобы исправить это, обязательно определите my_list
вне функции, чтобы она находилась в правильной области:
my_list = []
def my_func():
my_list.append(1)
my_func()
Войти в полноэкранный режимВыйти из полноэкранного режима
3. Злоупотребление return
заявление
Другой распространенной причиной сообщения об ошибке «AttributeError: объект NoneType не имеет атрибута ‘append’» является неправильное использование return
заявление.
Например, предположим, что у вас есть следующий код:
def my_func():
my_list = []
return my_list.append(1)
result = my_func()
Войти в полноэкранный режимВыйти из полноэкранного режима
В этом случае мы пытаемся вернуть результат my_list.append(1)
. Однако, append()
не возвращает значение — он изменяет список на месте. Это значит, что my_func()
на самом деле возвращается None
и когда мы пытаемся присвоить результат result
получаем сообщение об ошибке.
Чтобы исправить это, просто верните my_list
вместо:
def my_func():
my_list = []
my_list.append(1)
return my_list
result = my_func()
Войти в полноэкранный режимВыйти из полноэкранного режима
Заключение
Сообщение об ошибке «AttributeError: ‘NoneType’ object has no attribute ‘append’» может вызывать разочарование, но обычно оно вызвано простыми ошибками, такими как забывание присвоить значение переменной или неправильное использование return
заявление. Понимая, что вызывает эту ошибку и как ее исправить, вы можете сэкономить много времени на отладку в будущем.
The AttributeError: ‘NoneType’ object has no attribute ‘append’ error happens when the append() attribute is called in the None type object. The NoneType object has no attribute like append(). That’s where the error AttributeError: ‘NoneType’ object has no attribute ‘append’ has happened.
The python variables, which have no value initialised, have no data type. These variables are not assigned any value, or objects. These python variable does not support append() attribute. when you call append() attribute in a None type variable, the exception AttributeError: ‘NoneType’ object has no attribute ‘append’ will be thrown.
If nothing is assigned to the python variable, the variable can not be used unless any value or object is assigned. Calling the attribute of this variable value is pointless. If you call an attribute like append() the exception AttributeError: ‘NoneType’ object has no attribute ‘append’ will be thrown.
Exception
If python throws the attribute error, the error stack will be seen as below. The AttributeError: ‘NoneType’ object has no attribute ‘append’ error would display the line where the error happened.
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
a.append(' World')
AttributeError: 'NoneType' object has no attribute 'append'
[Finished in 0.0s with exit code 1]
How to reproduce this issue
If a python variable is created without assigning an object or value, it contains None. If the attribute is called with the python variable, the error will be thrown. The exception is thrown by calling an attribute from a variable that has no object assigned to it.
Program
a = None;
a.append(' World')
print a
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
a.append(' World')
AttributeError: 'NoneType' object has no attribute 'append'
[Finished in 0.0s with exit code 1]
Root Cause
The python class is a collection of data and functionality. The object in python is an enclosed collection of data and functionality identified as a class variable. The attribute in python is the collection of class-related data and functionality. These attributes are available for all class objects. The Attribute error is thrown if a variable has no object assigned is invoked.
The dot operator is used to reference to a class attribute. The reference attribute is made with an attribute that is not available in a class that throws the attribute error in python. The attribute is called in a variable that is not associated with any object of the class, which will also cause the attribute error AttributeError: ‘NoneType’ object has no attribute ‘append’.
Solution 1
The none type variable must be assigned with a value or object. If the variable has valid object that contains attributes such as append(), the error will be resolved. Otherwise, the variable is used with basic python operators such as arithmetic operator.
In the example below a variable contains a “Hello” string. Append method to concatenate with another “world” string is invoked In python, two strings are concatenated by using the arithmetic addition operator. This attribute error is fixed by replacing the append attribute with the arithmetic addition operator.
Program
a = 'Hello'
a = a +' World'
print a
Output
Hello World
Solution 2
If the python variable does not required to assign a value, the python variable should be assigned with empty list. The empty list will add a value if the append() function is called in the code. The example below contains a python variable that is assigned with an empty list. if the append() function is called, the value is added in the empty list.
Program
a = []
a.append(' World')
print a
Output
[' World']
[Finished in 0.0s]
Solution 3
Due to the dynamic creation of the variable the python variable may not be assigned with values. The datatype of the variable is unknown. In this case, the None data type must be checked before the an attribute is called.
Program
a = None;
if a is not None:
a.append(' World')
print a
Output
None
[Finished in 0.1s]
Solution 4
The python variable should be validated for the expected data type. If the variable has the expected data type, then the object attribute should be invoked. Otherwise, the alternate flow will be invoked.
If the variable contains the excepted type of the value, the if block will execute. Otherwise, the else block will execute. This will eliminate the error AttributeError: ‘NoneType’ object has no attribute ‘append’.
Program
a = [];
if type(a) is list:
a.append(' World')
else :
a =a;
print a
Output
[' World']
[Finished in 0.0s]
Solution 5
If the data type of the variable is unknown, the attribute will be invoked with try and except block. The try block will execute if the python variable contains value or object. Otherwise, the except block will handle the error.
In the example below, the append attribute is called within the try block. If any error occurs the except block will be executed. The error will not be thrown.
Program
a = None;
try :
a.append(' World')
except :
print 'error';
print a
Output
error
Hello
[Finished in 0.0s]