Python
AttributeError
List Object
Debugging
Python Errors

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

Codemia Knowledge Hub ·

add() is a method of set, not list, so calling it on a list raises AttributeError: 'list' object has no attribute 'add'. Use append() to add one item to a list, or switch to a set if what you really want is a collection of unique values.

Why lists have no add

A list is an ordered sequence that allows duplicates. A set is an unordered collection of unique items. The two have different semantics, so their method names differ.

This code fails:

python
items = [1, 2, 3]
items.add(4)

list does not define add. Its API offers append, extend, insert and other sequence operations instead.

Use append or extend for lists

To add one element to the end of a list, use append:

python
items = [1, 2, 3]
items.append(4)
print(items)

To add several values from another iterable, use extend:

python
items = [1, 2, 3]
items.extend([4, 5, 6])
print(items)

append adds one object, while extend iterates over the collection and adds each element separately. Mixing them up is easy:

python
items = [1, 2, 3]
items.append([4, 5])
print(items)

This produces a nested list, because the whole inner list is appended as one element.

Use a set when uniqueness is the goal

The error can be a hint that the wrong container was chosen. If the code wants unique elements and an add operation, a set may be the right type:

python
1items = {1, 2, 3}
2items.add(4)
3items.add(4)
4print(items)

The second add creates no duplicate, because sets enforce uniqueness.

  • Use a list when order matters or duplicates are meaningful.
  • Use a set when uniqueness and fast membership tests matter more than order.

Swapping .add() for .append() without checking whether uniqueness was required can be the wrong fix: duplicates will start to appear.

Check the variable's type at runtime

In larger programs, the error often means a variable changed type earlier and later code still assumes the old type. Check what it actually is:

python
print(type(items))

If items was meant to be a set but became a list through reassignment, the real bug is upstream, and fixing only the .add() line hides it. The same applies if you carried over habits from another language where list-like containers have an add method: Python lists do not.


Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms