Borislav Hadzhiev
Last updated: Apr 20, 2022
Check out my new book
The Python "AttributeError: 'list' object has no attribute 'encode'" occurs
when we call the encode()
method on a list instead of a string. To solve the
error, call encode()
on a string, e.g. by accessing the list at a specific
index or by iterating over the list.
Here is an example of how the error occurs.
my_list = ['apple', 'banana', 'kiwi'] # ⛔️ AttributeError: 'list' object has no attribute 'encode' my_list.encode('utf-8')
We created a list with 3 elements and tried to call the encode()
method on the
list which caused the error.
encode()
method is string-specific, so we have to call it on a string, and not on a list object.One way to solve the error is to access the list at a specific index before
calling encode()
.
my_list = ['apple', 'banana', 'kiwi'] result = my_list[0].encode('utf-8') print(result) # 👉️ b'apple'
We accessed the list element at index 0
and called the encode()
method on
the string.
If you need to call the encode()
method on each string in a list, use a list
comprehension.
my_list = ['apple', 'banana', 'kiwi'] new_list = [word.encode('utf-8') for word in my_list] print(new_list) # 👉️ [b'apple', b'banana', b'kiwi']
Alternatively you can use a for
loop to call the encode()
method on each
string in the list.
my_list = ['apple', 'banana', 'kiwi'] for word in my_list: result = word.encode('utf-8') print(result)
We used a for
loop to iterate over the list and called the encode()
method
on each string.
The str.encode
method returns an encoded version of the string as a bytes object. The default
encoding is utf-8
.
encode()
method on a list instead of a string.To solve the error, you either have to correct the assignment of the variable
and make sure to call encode()
on a string, or call encode()
on an element
in the list that is of type string
.
You can either access the list at a specific index, e.g. my_list[0]
or use a
for loop to iterate over the list if you have to call encode()
on each
element.
You can view all the attributes an object has by using the dir()
function.
my_list = ['a', 'b', 'c'] # 👉️ [... 'append', 'clear', 'copy', 'count', 'extend', 'index', # 'insert', 'pop', 'remove', 'reverse', 'sort' ...] print(dir(my_list))
If you pass a class to the dir() function, it returns a list of names of the classes' attributes, and recursively of the attributes of its bases.
If you try to access any attribute that is not in this list, you would get the "AttributeError: list object has no attribute" error.
Since encode()
is not a method implemented by lists, the error is caused.