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

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

1 · The lesson

read

What this error means

You called a method that lists don't have. There are three common reasons. You remembered the method name wrongly. Or you used a name from another language (JavaScript's .push, Java's .add, C#'s .Length). Or the variable is 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

There are two kinds of mistake:

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, but 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 see this in real code

  • A JavaScript developer's first day with Python: items.push(x).
  • A Java developer: items.size().
  • A pandas DataFrame method called on a list: df_list.head() doesn't work if df_list is a Python list, not a DataFrame.
  • Calling a string method on a list: result.split(",") when result is already a list of strings.

See Also

Found this useful? Share it with a friend who’s learning Python.