How to solve the attribute error: ‘list’ object has no attribute ‘find’?

Today we will help you to troubleshoot an error that you might encounter when searching for a specific element in a Python list object.

Understanding the list object has no find attribute exception

To reproduce the error simply run this short snippet in your Jupyter Notebook, Spyder, VS Code, PyCharm or other Python editor:

my_lst = ['This', 'website', 'teaches', 'Python', 'coding']
my_lst.find('coding') # this will generate an error

You will receive the following exception:

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

What is the root cause for the error message? The problem is that you are using the find method, that is available for strings on a Python list. When applied on strings the find method returns the index in the string where the substring we are searching for is first found. When find() returns a value that is greater than -1 it means that a substring is contained in the string.

Tip: When in doubt, always make sure to use the help function to find out the available method for your object

Solving the attribute error find in lists

Here are two methods that you can use in order to search inside a list:

Using the index() method

The index method returns the index number of a specific element in the list:

e = 'coding' # the element we are searching for

if my_lst.index(e) > -1:
        print (f'The list contains element: {e}')
else:
    print (f'The list doesn\'t contain element: {e}' )

Using the in operator

We can use the in operator to find if an element is contained in the list:

e = 'coding' # the element we are searching for

if e in my_lst:
    print (f'The list contains element: {e}')
else:
    print (f'The list doesn\'t contain element: {e}' )

Both options will return the following result:

The list contains element: coding