AttributeError: 'list' object has no attribute 'len'


Borislav Hadzhiev

Wed Apr 20 20222 min read


Photo by Y K

AttributeError: 'list' object has no attribute 'len' #

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 the len function to get its length, e.g. len(['a', 'b']).

attributeerror list object has no attribute len

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 len attribute.

To get the list's length, pass it to the len() function.
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.

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

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[0]) 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 for loop.
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 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.