AttributeError: list object has no attribute len error occurs while invoking len as attribute from list class in the place of the passing list to len() function. In this article, we will first replicate the issue and then fix it.
AttributeError: list object has no attribute len ( replicate ) –
Firstly we will initialize the dummy list and then invoke the len() function with it. Here is the code for this.
As you can see we have first initialized sample_list first and then invoke len() with it. This is how we get this arrtibuteerror.
AttributeError: list object has no attribute len (Solution) –
There is very simple way to fix this error. All we need to pass the entire list into len() function rather than invoking it. Here is the way to perform this.
Let’s see the output for the above code.
Actually, this is just confusion in the way of invoking. Since len is not an available attribute in the list.
What is attributeError (Bonus Point)?
AttributeError always occurs because of referring to any attribute that either does not exist or refers to a different class at all. The best way to fix this error is to make it compatible with an attribute or call a relevant attribute with a relevant class. If you want to understand more about AttributeError, Please read the below article-
What is AttributeError in Python ? Complete Overview
If you want to specifically understand about attributeError then read the below article-
AttributeError: list object has no attribute [ Attribute_Name] ( Solved )
Other Work Around to check len ( Not recommended )-
If you want to replace the len() function with the custom logic then we need to run a loop over the complete list ( assuming you know the last element and it is unique ) and increment a variable in each cycle. The final Value of the incremented variable will be the length of the list.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.