How to Solve Python AttributeError: ‘list’ object has no attribute ‘endswith’

by | Programming, Python, Tips

This error occurs when you try to call the string method endswith() on a list object.

You can solve this error by accessing the items in the list using indexing syntax or a for loop and if the items are strings, you can call the endswith() method. For example,

list_of_sites = ['bloomberg.com', 'ft.com', 'forbes.com', 'princeton.edu']

for site in list_of_sites:
    if site.endswith('.edu'):
        print(f'Educational institution: {site}')

This tutorial will go through how to solve the error with code examples.


AttributeError: ‘list’ object has no attribute ‘endswith’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The part “‘list’ object has no attribute ‘endswith’” tells us that the list object does not have the attribute endswith().

The endswith() method belongs to the string data type and returns True if a string ends with the specified suffix. Otherwise, it returns False.

We can check an object’s attributes by using the dir() function. The dir() function returns all the properties and methods of the specified object as a list.

Let’s verify that endswith() is not a list method by using the in operator to check if the method exists in the list object returned by dir():

pizzas = ['margherita', 'pepperoni', 'tartufo']

attributes = dir(pizzas)

print('endswith' in attributes)
False

The membership operation returns False for the list object.

Let’s prove that endswith() is a str method by using the in operator:

string = "Python"

attributes = dir(string)

print('endswith' in attributes)
True

The membership operation returns True for the str object.

Example

Let’s look at an example of trying to call endswith() on a list object.

list_of_sites = ['bloomberg.com', 'ft.com', 'forbes.com', 'princeton.edu']

if list_of_sites.endswith('.edu'):
    print(f'Educational institution: {site}')

In the above code, we define a list of strings representing four different websites. Websites that belong to US educational institutions end with the domain ‘.edu’.

We attempt to extract the educational institutional website by searching for the .edu suffix using the endswith() method in an if statement. Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [33], in <cell line: 3>()
      1 list_of_sites = ['bloomberg.com', 'ft.com', 'forbes.com', 'princeton.edu']
----> 3 if list_of_sites.endswith('.edu'):
      4     print(f'Educational institution: {site}')

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

The error occurs because we are trying to call the endswith() method on a list object. The endswith() method is an attribute of the str class not the list class.

Solution

We can solve this error by iterating over the list using a for loop and call the endswith() method on each item in the loop. We can verify that the items in the list are strings using the built-in type() method.

Let’s look at the revised code:

list_of_sites = ['bloomberg.com', 'ft.com', 'forbes.com', 'princeton.edu']

for site in list_of_sites:
    print(type(site))
    if site.endswith('.edu'):
        print(f'Educational institution: {site}')

Let’s run the code to see the result:

<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
Educational institution: princeton.edu

We correctly used the endswith() method to find the website ending with ‘.edu‘ and printed it to the console.

We can also use list comprehension to make a new list based on the values of an existing list.

Let’s look at an example of a list with more than one ‘.edu‘ website. We want to store the educational institution websites in a new list

list_of_sites = ['bloomberg.com', 'harvard.edu','ft.com', 'forbes.com', 'princeton.edu']

edu_sites = [site for site in list_of_sites if site.endswith('edu')]

print('Educational institution sites:\n',edu_sites)

The list comprehension calls the endswith() method on each string in list_of_sites. Let’s run the code to see the result:

Educational institution sites:
 ['harvard.edu', 'princeton.edu']

We successfully extracted the websites ending with ‘.edu‘ and stored them in a new list.

We can also access individual items in a list using indexing syntax. For example,

list_of_sites = ['bloomberg.com', 'harvard.edu','ft.com', 'forbes.com', 'princeton.edu']

print(list_of_sites[0].endswith('.edu'))

As each item in list_of_sites is a string we can use indexing syntax, [], to access the first item and call the endswith() method. Let’s run the code to see the result:

False

Summary

Congratulations on reading to the end of this tutorial!

For further reading on AttributeErrors, go to the article:

How to Solve Python AttributeError: ‘list’ object has no attribute ‘startswith’

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨