AttributeError: object has no attribute
The value has no method or attribute by that name. The message names the value's type and what was asked for.
Your error
Check these first
- Spelling. Method names have to be exact:
append, notapendorAppend. - What type is it?
print(type(x)): lists, strings and dictionaries each have their own methods. - Your file's name. A file named like a module, such as
random.pyormath.py, hides that module. Rename it.
Causes and fixes
1 A typo in the name
When Python can guess the name you meant, it says so at the end of the message.
nums = [1, 2]
nums.apend(3)
print(nums)
AttributeError: 'list' object has no attribute 'apend'. Did you mean: 'append'?
nums = [1, 2]
nums.append(3)
print(nums)
[1, 2, 3]
2 The value is None
nums.sort() sorts the list itself and gives back None, as does any function without a return. Don't store what it gives back.
nums = [3, 1, 2]
nums = nums.sort()
nums.append(4)
AttributeError: 'NoneType' object has no attribute 'append'
nums = [3, 1, 2]
nums.sort()
nums.append(4)
print(nums)
[1, 2, 3, 4]
3 A method of another type
append() belongs to lists and split() to strings. Check what the value is, and use that type's way of doing it: strings join with +.
name = "Ada"
name.append("!")
print(name)
AttributeError: 'str' object has no attribute 'append'
name = "Ada"
name = name + "!"
print(name)
Ada!
4 A file named like a module
If your own file is called random.py, math.py or turtle.py, import random loads your file instead of Python's module, and it has none of the module's functions. Rename your file, for example to dice.py.
Still stuck?
- In the traceback,
File "main.py", line 3says where the error happened. In the editor, click that line to go to it. - Go over the basics: Lists
- Other errors: FileNotFoundError, IndentationError, IndexError, KeyError, ModuleNotFoundError, NameError, RecursionError, SyntaxError, TypeError, UnboundLocalError, ValueError, ZeroDivisionError