How To Solve AttributeError: ‘list’ object has no attribute ‘len’ in Python

When you want to get the length of an object in Python, we can use the len() function to do it. However, calling the len() method on the object is a bad practice, resulting in the error AttributeError: ‘list’ object has no attribute ‘len’ . The article will present the correct syntax and usage of the len() function. Let’s go into the specific situation and figure out how to fix it.

What causes the error AttributeError: ‘list’ object has no attribute ‘len’ in Python?

The error AttributeError: ‘list’ object has no attribute ‘len’ occurs when we access the len() method on a List object. This is not the correct way to get the length of a List. Let’s review the syntax of the len() method.

The len() is a function that helps measure an object’s length. This object can be a List, a string, etc

Syntax:

len(object)

Parameter:

object: is an object, this parameter is required

Return Value:

The return result will be the number of items in the object.

You can see that it is incorrect to use the len() function on a List object. You must pass the List object into the len() function.

Example of error that occurred:

fruits = ["apple", "banana", "cherry"]

# Wrong use of "len()" function
print(fruits.len())

Output:

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

Solutions for AttributeError: ‘list’ object has no attribute ‘len’

To solve this error, we should use the correct syntax provided by the len() function and remember that the List object does not have such a len() method. Or you can use the method below

Using For loop

Because you can iterate through each element of the List, you can use a For loop to count the number of elements of the List.

Example:

fruits = ["apple", "banana", "cherry"]
counter = 0

# Use a For loop to count the number of elements of the List
for fruit in fruits:
    counter = counter + 1
print(f"The length of List is: {counter}")

Output:

The length of List is: 3

Using length_hint()

If you don’t want to use the len() function, you can use a rarely used function called length_hint() to calculate the length of the List. You need to import this function first.

Example:

from operator import length_hint

fruits = ["apple", "banana", "cherry"]

# Use length_hint() to calculate the length of the List
print(f"The length of List is: {length_hint(fruits)}")

Output:

The length of List is: 3

You can refer to this article to learn more about the error.

Summary

The error AttributeError: ‘list’ object has no attribute ‘len’ has been resolved. Just remember that passing the object to the function len() and not calling this method from the object can solve the problem. We hope you like it. Good luck to you!

Leave a Reply

Your email address will not be published. Required fields are marked *