PythonMastery
reference 3 min read · lesson 8 of 45 in Errors

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

1 · The lesson

read

What this error means

You called a method on a list that lists simply don't have. Either you misremembered the method name, you're translating from another language (JavaScript's .push, Java's .add, C#'s .Length), or the variable isn't the list-of-objects you think it is — it's a list, but you wanted to call the method on one of its elements.

When you see it

python
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    items.add(42)
AttributeError: 'list' object has no attribute 'add'

Why it happens

Two flavours:

1. Wrong method name. Python lists use .append, .extend, .insert, .remove, .pop, .sort, .reverse. They don't have .add, .push, .length, .size, or .contains.
2. Wrong level. You have a list of objects but you're calling the object's method on the list. users.upper() doesn't work; users[0].upper() does.

How to fix it

Quick translation table for newcomers:

You wanted (other language)Python equivalent
arr.push(x) (JS), list.add(x) (Java)arr.append(x)
arr.pop() endarr.pop() (same)
arr.length (JS), arr.Length (C#), arr.size() (Java)len(arr)
arr.contains(x) (Java)x in arr
arr.indexOf(x) (JS)arr.index(x)
arr.concat(other) (JS)arr + other or arr.extend(other)
arr.includes(x) (JS)x in arr
arr.toString()str(arr) or ",".join(arr)
arr.forEach(fn)for x in arr: fn(x)
arr.map(fn)[fn(x) for x in arr]
arr.filter(fn)[x for x in arr if fn(x)]
arr.reduce(fn, init)functools.reduce(fn, arr, init)

Loop or comprehension when the method belongs to the elements:

python
names = ["alice", "bob"]
# names.upper()                  # AttributeError
shouty = [n.upper() for n in names]

Use len() not .length:

python
items = [1, 2, 3]
print(len(items))                # not items.length

When you'd actually see this in real code

  • A JS developer's first day in Python: items.push(x).
  • A Java developer: items.size().
  • Pandas DataFrame method called on a list: df_list.head() won't work if df_list is a Python list, not a DataFrame.
  • Forgetting to unwrap a result: result.split(",") when result is already a list of strings.

See Also