Borislav Hadzhiev
Last updated: Apr 20, 2022
Check out my new book
The Python "TypeError: descriptor 'append' for 'list' objects doesn't apply to
a 'str' object" occurs when we call the append()
method on the list
class.
To solve the error, call the method on an instance of the class instead, e.g.
list().append('a')
.
Here is an example of how the error occurs.
# ⛔️ TypeError: descriptor 'append' for 'list' objects doesn't apply to a 'str' object list.append('hello')
We called the append
method on the list
class which caused the error.
We should instead call the append()
method on a list
object.
my_list = list() my_list.append('apple') my_list.append('banana') print(my_list) # 👉️ ['apple', 'banana']
We used parenthesis to instantiate the list class and called the append()
method on an instance of the class.
Note that a much more common way to declare a variable that stores a list is to use square brackets.
my_list = [] print(type(my_list)) # 👉️ <class 'list'> my_list.append('apple') my_list.append('banana') print(my_list) # 👉️ ['apple', 'banana']
The example above achieves the same result.
The list.append() method adds an item to the end of the list.
my_list = ['a', 'b', 'c'] my_list.append('d') print(my_list) # 👉️ ['a', 'b', 'c', 'd']
The method returns None
as it mutates the original list.
append()
in a variable because the method mutates the original list in place and returns None
.If you need to append multiple values to a list, use the extend()
method
instead.
The list.extend method takes an iterable (such as a list) and extends the list by appending all of the items from the iterable.
my_list = ['a', 'b'] my_list.extend(['c', 'd', 'e']) print(my_list) # 👉️ ['a', 'b', 'c', 'd', 'e']
The list.extend
method returns None
as it mutates the original list.
You can print the list
class and an instance of the class to see the
difference between the two.
print(list) # 👉️ <class 'list'> print(list()) # 👉️ []
The first call to the print
function prints the class, whereas the second
prints an instance of the class.
You first have to instantiate the list
class in order to use methods like
append
.