Last updated: Apr 8, 2024
Reading time·2 min
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') # ⛔️ TypeError: list.append(1)
We called the append
method on the list
class which caused the error.
append()
method on a list objectInstead, call the append()
method on a list
object.
my_list = list() my_list.append('bobby') my_list.append('hadz') my_list.append('com') print(my_list) # 👉️ ['bobby', 'hadz', 'com']
We used parentheses 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('bobby') my_list.append('hadz') my_list.append('com') print(my_list) # 👉️ ['bobby', 'hadz', 'com']
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.
Make sure to not store the result of calling list.append()
in a variable.
a_list = [] # ⛔️ don't do this result = a_list.append('bobbyhadz.com') print(result) # 👉️ None print(a_list) # 👉️ ['bobbyhadz.com']
Notice that the result
variable stores a None
value because the
list.append()
method mutates the original list 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 to use methods like append
.
You can learn more about the related topics by checking out the following tutorials: