Borislav Hadzhiev
Last updated: Apr 20, 2022
Check out my new book
The "AttributeError: 'list' object has no attribute 'size'" occurs when we
access the size
attribute on a list. To solve the error, pass the list to the
len
function to get its length, e.g. len(['a', 'b'])
.
Here is an example of how the error occurs.
my_list = ['apple', 'banana', 'kiwi'] # ⛔️ AttributeError: 'list' object has no attribute 'size' print(my_list.size)
The error was caused because list objects don't have a size
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.
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.