Wed Apr 20 2022·2 min read
Photo by Y K
The Python "AttributeError: 'list' object has no attribute 'len'" occurs when
we access the
len attribute on a list. To solve the error, pass the list to
len function to get its length, e.g.
Here is an example of how the error occurs.
my_list = ['apple', 'banana', 'kiwi'] # ⛔️ AttributeError: 'list' object has no attribute 'len' print(my_list.len())
The error was caused because list objects don't have a
To get the list's length, pass it to the
my_list = ['apple', 'banana', 'kiwi'] result = len(my_list) print(result) # 👉️ 3
The len() function returns the length (the number of items) of an object.
If you need to get the length of an item in the list, access the list at the specific index.
my_list = ['apple', 'banana', 'kiwi'] result = len(my_list) print(result) # 👉️ 5
We accessed the list at index
0 and passed the result to the length function.
If you need to get the length of every element in the list, use a
my_list = ['apple', 'banana', 'kiwi'] for fruit in my_list: print(len(fruit))
You can view all the attributes an object has by using the
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.