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

LBes's user avatar

LBes

3,3561 gold badge31 silver badges64 bronze badges

asked Oct 15, 2012 at 11:35

learner's user avatar

0

list is mutable

Change

last_list=last_list.append(p.last_name)

to

last_list.append(p.last_name)

will work

Uma Madhavi's user avatar

Uma Madhavi

4,8315 gold badges38 silver badges73 bronze badges

answered Apr 29, 2017 at 7:18

jessiejcjsjz's user avatar

jessiejcjsjzjessiejcjsjz

1,7811 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 Julien's user avatar

Cédric JulienCédric Julien

78.1k15 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.

Ru Chern Chong's user avatar

answered Jan 1, 2020 at 13:45

Jayesh Mishra's user avatar

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 Day's user avatar

Joe DayJoe Day

6,8854 gold badges24 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!

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]

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! 😃

The Python append() method returns a None value. This is because appending an item to a list updates an existing list. It does not create a new one.

If you try to assign the result of the append() method to a variable, you encounter a “TypeError: ‘NoneType’ object has no attribute ‘append’” error.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

In this guide, we talk about what this error means, why it is raised, and how you can solve it, with reference to an example.

TypeError: ‘NoneType’ object has no attribute ‘append’

In Python, it is a convention that methods that change sequences return None. The reason for this is because returning a new copy of the list would be suboptimal from a performance perspective when the existing list can just be changed.

Because append() does not create a new list, it is clear that the method will mutate an existing list. This prevents you from adding an item to an existing list by accident.

A common mistake coders make is to assign the result of the append() method to a new list. This does not work because append() changes an existing list. append() does not generate a new list to which you can assign to a variable.

An Example Scenario

Next, we build a program that lets a librarian add a book to a list of records. This list of records contains information about the author of a book and how many copies are available.

Let’s start by defining a list of books:

books = [
	{ "title": "The Great Gatsby", "available": 3 }
]

The books list contains one dictionary. A dictionary stores information about a specific book.  We add one record to this list of books:

books = books.append(
	{ "title": "Twilight", "available": 2 }
)

Our “books” list now contains two records. Next, we ask the user for information about a book they want to add to the list:

title = input("Enter the title of the book: ")
available = input("Enter how many copies of the book are available: ")

Now that we have this information, we can proceed to add a record to our list of books. We can do this using the append() method:

books = books.append(
	{ "title": title, "available": int(available) }
)

We’ve added a new dictionary to the “books” list. We have converted the value of “available” to an integer in our dictionary. We assign the result of the append() method to the “books” variable. Finally, we print the new list of books to the console:

Let’s run our code and see what happens:

Enter the title of the book: Pride and Prejudice
Enter how many copies of the book are available: 5
Traceback (most recent call last):
  File "main.py", line 12, in <module>
	books = books.append(
AttributeError: 'NoneType' object has no attribute 'append'

Our code successfully asks us to enter information about a book. When our code tries to add the book to our list of books, an error is returned.

The Solution

Our code returns an error because we’ve assigned the result of an append() method to a variable. Take a look at the code that adds Twilight to our list of books:

books = books.append(
	{ "title": "Twilight", "available": 2 }
)

This code changes the value of “books” to the value returned by the append() method. append() returns a None value. This means that “books” becomes equal to None.

When we try to append the book a user has written about in the console to the “books” list, our code returns an error. “books” is equal to None and you cannot add a value to a None value.

To solve this error, we have to remove the assignment operator from everywhere that we use the append() method:

books.append(
	{ "title": "Twilight", "available": 2 }
)

…

books.append(
	{ "title": title, "available": int(available) }
)

We’ve removed the “books = ” statement from each of these lines of code. When we use the append() method, a dictionary is added to books. We don’t assign the value of “books” to the value that append() returns.

Let’s run our code again:

Enter the title of the book: Pride and Prejudice
Enter how many copies of the book are available: 5
[{'title': 'The Great Gatsby', 'available': 3}, {'title': 'Twilight', 'available': 2}, {'title': 'Pride and Prejudice', 'available': 5}]

Our code successfully adds a dictionary entry for the book Pride and Prejudice to our list of books.

Conclusion

The “TypeError: ‘NoneType’ object has no attribute ‘append’” error is returned when you use the assignment operator with the append() method.

To solve this error, make sure you do not try to assign the result of the append() method to a list. The append() method adds an item to an existing list. The method returns None, not a copy of an existing list.

Now you’re ready to solve this common Python problem like a professional!

Понравилась статья? Поделить с друзьями:
  • Nod32 ошибка обновления 0x1106 nod32
  • Nod32 ошибка win 1632
  • Nod32 ошибка 2502
  • Nod 32 ошибка активации act 0
  • Nod 32 ошибка 0x1106