Fixed AttributeError: ‘NoneType’ object has no attribute ‘append’

The exception or error message AttributeError: ‘NoneType’ object has no attribute ‘append’ shows up because there is an attempt to use the append attribute of the object, and this object is of type NoneType. If the object is a list, no problem because a list object has an append attribute. This error is usually encountered by people new to Python as part of a bug thinking that an object has an attribute but actually has not because of a bug. In this article, we will discuss this exception and how to avoid it.

1.  What is the problem?

1.1.  What is Attribute

Attributes are connected with an object. Object can have data and function or method attributes. An object can be defined through a class. Let us create an example object with attributes.

code

class Car:
    def __init__(self, num_wheels=4):
        self.num_wheels = num_wheels  # data attribute
        self.is_start = False  # data attribute
        
    def start(self):
        """function or method attribute"""    
        self.is_start = True
        print('engine is starting')
        
    def stop(self):
        """function or method attribute"""
        self.is_start = False
        print('engine is stopped')
        
# Instantiate a car
car = Car(4)
print(f'num wheels is {car.num_wheels}')

# Start the car
car.start()
print(f'car start state is {car.is_start}')

output

num wheels is 4
engine is starting
car start state is True

Our object is a car, with attributes num_wheels, is_start, start(), and stop(). To call an attribute, we use the dot notation object.attribute.

1.2.  Object

Objects can have different types or class, it can be an intboolfloatlistdictNoneyType, and others. That append attribute is an attribute of the list object. It is used to add items to the list.

code

fruits = ['banana', 'jackfruit']  # a list of fruits
fruits.append('mango')  # add mango
# output ['banana', 'jackfruit', 'mango']

1.3.  Reproduce the error message

Let us now try to reproduce the error message AttributeError: ‘NoneType’ object has no attribute ‘append’. We have a function that is supposed to return a list of top oil companies. We then add a new company to this list.

code

def oil_companies():
    """Returns a list of top oil companies."""
    top_oil_companies = [
        'Saudi Arabian Oil Co. (Saudi Aramco) (Tadawul: 2222)',
        'PetroChina Co. Ltd. (PTR)',
        'China Petroleum & Chemical Corp. (SNP)',
        'Exxon Mobil Corp. (XOM)',
        'TotalEnergies SE (TOT)'
    ]

# Get a list of top oil companies.
oil_com = oil_companies()

# New company to be added or appended.
new_company = 'BP PLC (BP)'

# Add or append the new company.
oil_com.append(new_company)

output

PS F:\Project\kodlogs> python art7.py
Traceback (most recent call last):
  File "F:\Project\kodlogs\art7.py", line 18, in <module>
    oil_com.append(new_company)
AttributeError: 'NoneType' object has no attribute 'append'

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

What is wrong here? The issue with the code is I never return the list in oil_companies function. And with that our variable oil_com is None.

code

# Get a list of top oil companies.
oil_com = oil_companies()
print(f'oil_com value is {oil_com}')

output

oil_com value is None

To get the type of oil_com variable we can use the built-in function type(object).

code

print(f'oil_com type is {type(oil_com)}')

output

oil_com type is <class 'NoneType'>

So the type of oil_com is NoneType. Then the append attribute is used in:

oil_com.append(new_company)

This is why we get that error message. The oil_com is Nonetype and does not have the append attribute. We thought that the function oil_companies() would return a list.

In the next section, I will show how to solve this issue.

2. Solution: How to avoid this error?

To avoid this type of exception, we should not append an item to a NoneType object.

Incorrect

mylist = None
mylist.append(1)  # error message

correct

mylist = [2, 3]
mylist.append(1)  # [2, 3, 1]

Let us now solve the issue with the oil company’s function from section 1. Just add a return statement. See the following code.

code

def oil_companies():
    """Returns a list of top oil companies."""
    top_oil_companies = [
        'Saudi Arabian Oil Co. (Saudi Aramco) (Tadawul: 2222)',
        'PetroChina Co. Ltd. (PTR)',
        'China Petroleum & Chemical Corp. (SNP)',
        'Exxon Mobil Corp. (XOM)',
        'TotalEnergies SE (TOT)'
    ]
    return top_oil_companies  # <------------------- add this

# Get a list of top oil companies.
oil_com = oil_companies()
print(oil_com)

# New company to be added or appended.
new_company = 'BP PLC (BP)'

# Add or append the new company.
oil_com.append(new_company)
print(oil_com)

output

['Saudi Arabian Oil Co. (Saudi Aramco) (Tadawul: 2222)',
 'PetroChina Co. Ltd. (PTR)', 'China Petroleum & Chemical Corp. (SNP)',
 'Exxon Mobil Corp. (XOM)', 'TotalEnergies SE (TOT)']
['Saudi Arabian Oil Co. (Saudi Aramco) (Tadawul: 2222)',
 'PetroChina Co. Ltd. (PTR)', 'China Petroleum & Chemical Corp. (SNP)',
 'Exxon Mobil Corp. (XOM)', 'TotalEnergies SE (TOT)', 'BP PLC (BP)']

3.  Conclusion

We will encounter the exception message AttributeError: ‘NoneType’ object has no attribute ‘append’ if we try to use the append attribute or method to a NoneType object because it has no append attribute. However, the append is available in a list object.