Nonetype object has no attribute append ошибка

I have two lists that I’m merging into a dictionary

keys = ['p2p', 'groupchat']
tests_available = ['p2p_1', 'p2p_2', 'p2p_3', 'groupchat_1', 'groupchat_2']

The expected output will be something like

{'p2p': ['p2p_1', 'p2p_2', 'p2p_3'], 'groupchat': ['groupchat_1', 'groupchat_2']
}

My code to create the dictionary is below.

out = {}
out = dict.fromkeys(keys)

for tests in tests_available:
    if tests.split('_')[0] in keys:
        key = tests.split('_')[0]
        out[key].append(tests)

However, it is throwing the error ‘NoneType’ object has no attribute ‘append’ when it is trying to append the values to the key. Can anyone help me identify what is wrong in my code?

asked Sep 23, 2016 at 10:09

jeffsia's user avatar

1

If you use a defaultdict then the append call will work as the value type defaults to a list:

In [269]:
from collections import defaultdict
keys = ['p2p', 'groupchat']
tests_available = ['p2p_1', 'p2p_2', 'p2p_3', 'groupchat_1', 'groupchat_2']
d = defaultdict(list)
for test in tests_available:
    k = test.split('_')[0]
    if k in keys:
        d[k].append(test)
d.items()

Out[269]:
dict_items([('p2p', ['p2p_1', 'p2p_2', 'p2p_3']), ('groupchat', ['groupchat_1', 'groupchat_2'])])

See the docs: https://docs.python.org/2/library/collections.html#defaultdict-examples

answered Sep 23, 2016 at 10:20

EdChum's user avatar

EdChumEdChum

373k198 gold badges808 silver badges561 bronze badges

5

Your values are set to None in fromkeys unless you explicitly set a value:

fromkeys(seq[, value])

Create a new dictionary with keys from seq and values set to value.
fromkeys() is a class method that returns a new dictionary. value defaults to None.

In your case you need to create lists as values for each key:

d = {k:[] for k in keys}

You can also do your if check using the dict:

d = {k:[] for k in keys}

for test in tests_available:
    k = tests.split('_', 1)[0]
    if k in d:
        d[k].append(test)

You can pass a value to use to fromkeys but it has to be immutable or you will be sharing the same object among all keys.

answered Sep 23, 2016 at 10:12

Padraic Cunningham's user avatar

For a small number of keys/tests a dictionary comprehension would work as well:

keys = ['p2p', 'groupchat']
tests_available = ['p2p_1', 'p2p_2', 'p2p_3', 'groupchat_1', 'groupchat_2']
out = {k: [v for v in tests_available if v.startswith(k)] for k in keys}

Demo:

>>> out
{'groupchat': ['groupchat_1', 'groupchat_2'], 'p2p': ['p2p_1', 'p2p_2', 'p2p_3']}

answered Sep 23, 2016 at 10:14

Eugene Yarmash's user avatar

Eugene YarmashEugene Yarmash

142k40 gold badges323 silver badges376 bronze badges

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

The Python

append()

is a list method to add a new element object at the end of the list. But if we use a

append()

method on a NoneType object, we encounter the

AttributeError: 'NoneType' object has no attribute 'append'

.

In this Python tutorial, we will explore this error and learn why it occurs and how to solve it. To understand the error better, we will discuss a typical scenario where most Python learners encounter this error.

So, let’s get started!

NoneType is a type for the None object, which has no value. Functions that don’t return anything has the return value ‘None’. When we use the append() method on the NoneType object, we receive the error

AttributeError: 'NoneType' object has no attribute 'append'

.

The error has two parts —

  1. Exception Type (

    AttributeError

    )
  2. Error Message (

    'NoneType' object has no attribute 'append'

    )


1. Exception Type (

AttributeError

)

AttributeError is one of the standard Python exceptions. It occurs when we try to access an unsupported attribute (property or method) using an object.

For example, the

append()

method is exclusive to Python lists. But if we try to apply it to a tuple object, we receive the AttributeError. This is because tuple objects do not have the

append()

method.

tuple_ = (1,2,3,4,5)
tuple_.append(6)  #error


Output

Traceback (most recent call last):
  File "/home/main.py", line 2, in <module>
    tuple_.append(6)  #error
AttributeError: 'tuple' object has no attribute 'append'


2. Error Message (

'NoneType' object has no attribute 'append'

)

The error message

'NoneType' object has no attribute 'append'

» tells us that the

append()

method is not supported on the

NoneType object

. This means we called the

append()

method on a variable whose value is

None

.


Example

# A None value object
a = None

# calling append() method on the None value
a.append(2)

print(a)


Output

Traceback (most recent call last):
File "main.py", line 5, in <module>
a.append(2)
AttributeError: 'NoneType' object has no attribute 'append'


Break the code

In the above example, we received the error at line 5 with the

a.append(2)

statement. The value of

a

is

None

, and None value does not have any

append()

method. Hence, we receive this error.


Causes of AttributeError: ‘NoneType’ object has no attribute ‘append’

There are many reasons for this error to occur:

  • Having a function that does not return anything or returns

    None

    explicitly.
  • Setting a variable to

    None

    explicitly.
  • Assigning a variable to the result of calling a function that does not return anything.
  • Having a function that returns a value only if the condition is met.


Common Example Scenario

The most common scenario when novice Python programmers commit this error is when they assign the return value of the

append()

method to a Python list variable name and try to call the

append()

method again on the same object. The append() method can only append a new value at the end of the list object, and it does not return any value, which means it returns

None

.


For Example

# list object
my_list = [1,2,3,4,5]

# return value of append method 
return_value = my_list.append(6)

print(return_value)


Output

None

From the output, you can see that we get

None

value when we try to assign the return value of

append()

method to a variable.

Many new Python learners do not know about the

None

return value of the

append()

method. They assign the append() method calling statement to the list object, which makes the list object value to

None

. And when they again try to append a new value to the list, they encounter the

AttributeError: 'NoneType' object has no attribute 'append'

Error.


For Example

Let’s write a Python program for to-do tasks. The program will ask the user to enter the 5 tasks that he/she wants to perform. We will store all those tasks using a list object,

todos

. To add the tasks entered by the user, we will use the list

append()

method.

# create a empty list
todos = []

for i in range(1,6):
    task = input(f"Todo {i}: ")

    # add the task to the todo list
    todos =  todos.append(task)

print("****Your's Today Tasks******")
for i in todos:
    print(i)


Output

Todo 1: workout
Todo 2: clean the house
Traceback (most recent call last):
File "main.py", line 8, in <module>
todos = todos.append(task)
AttributeError: 'NoneType' object has no attribute 'append'


Break the code

In the above example, we get the error at line 8 with the statement

todos = todos.append(task)

. The error occurs during the second iteration of the for loop when we pass the

Todo 2: clean the house

value as an input.

In the first iteration, when we pass the

Todo 1: workout

value, the

todos = todos.append(task)

statement set the value of

todos

to

None

, because the value returned by the

todos.append(task)

statement is None.

That’s why, in the second iteration, when Python tries to call the

append()

method on the

None

object, it threw the

AttributeError: 'NoneType' object has no attribute 'append'

error.


Solution

The solution to the above problem is straightforward. We do not need to assign the return value to any object when we use the append() method on a Python list. The simple call of the append() method on a list object will add the new element to the end of the list.

To solve the above example, we only need to ensure that we are not assigning the

append()

method return value our

todos

list.


Example Solution

# create a empty list
todos = []

for i in range(1,6):
    task = input(f"Todo {i}: ")

    # add the task to the todo list
    todos.append(task)

print("****Your's Today Tasks******")
for i in todos:
    print(i)


Output

Todo 1: workout
Todo 2: clean the house
Todo 3: have a shower
Todo 4: make the breakfast
Todo 5: start coding
****Your's Today Tasks******
workout
clean the house
have a shower
make the breakfast
start coding


Final Thoughts!

This was all about the most common Python error

AttributeError: 'NoneType' object has no attribute 'append'

. The error occurs when we try to call the append() method on a

None

value. To resolve this error, we need to ensure that we do not assign any

None

or return value of the

append()

method to a list object.

If you still get this error in your Python program, you can share your code in the Comment section. We will try to help you with debugging.


People are also reading:

  • Online Python Compiler

  • Read File in Python

  • Best Python Interpreters

  • Python SyntaxError: can’t assign to function call Solution

  • Python Multiple Inheritance

  • Python typeerror: list indices must be integers or slices, not str Solution

  • Class and Objects in Python

  • Python SyntaxError: unexpected EOF while parsing Solution

  • How to become a Python Developer?

  • How to Play sounds in Python?

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

Возможно, вам также будет интересно:

  • Non zero return code ошибка
  • Non zero exit code 2 pycharm ошибка
  • Non un errore ma una lezione не ошибка а урок
  • Non system disk or disk error как исправить ошибку
  • Non orthogonal matrix support 3d max ошибка

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии