AttributeError: 'list' object has no attribute 'add'

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

AttributeError: 'list' object has no attribute 'add' #

The Python "AttributeError: 'list' object has no attribute 'add'" occurs when we access the add attribute on a list. Use the append() or insert() methods to add an element to a list. If you have a list of set objects, access the list at a specific index before calling add().

attributeerror list object has no attribute add

Here is an example of how the error occurs.

main.py
my_list = ['a', 'b', 'c'] # ⛔️ AttributeError: 'list' object has no attribute 'add' my_list.add('d')

If you need to add an item to end of the list, use the append() method.

main.py
my_list = ['a', 'b', 'c'] my_list.append('d') print(my_list) # 👉️ ['a', 'b', 'c', 'd']

The list.append() method adds an item to the end of the list.

The method returns None as it mutates the original list.

If you need to add an item at a specific index, use the insert() method.

main.py
my_list = ['b', 'c'] my_list.insert(0, 'a') print(my_list) # 👉️ ['a', 'b', 'c']

The list.insert method inserts an item at a given position.

The method takes the following 2 parameters:

NameDescription
indexThe index of the element before which to insert
itemThe item to be inserted at the given index

If you have a list of set objects, access the list at an index before calling add().

main.py
my_list = [set(), set(), set()] my_list[0].add('hello') my_list[0].add('world') print(my_list[0]) # 👉️ {'world', 'hello'}

We accessed the list at index 0 and used the add() method to add items to the set().

If you need to add an element to each set in the list, use a for loop.

main.py
my_list = [set(), set(), set()] for s in my_list: s.add('hello') # 👇️ [{'hello'}, {'hello'}, {'hello'}] print(my_list)

You can view all the attributes an object has by using the dir() function.

main.py
my_list = ['a', 'b', 'c'] # 👉️ [... 'append', 'clear', 'copy', 'count', 'extend', 'index', # 'insert', 'pop', 'remove', 'reverse', 'sort' ...] print(dir(my_list))

If you pass a class to the dir() function, it returns a list of names of the classes' attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the "AttributeError: list object has no attribute" error.

Since add() is not a method implemented by lists, the error is caused.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.