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

by | Programming, Python, Tips

This error occurs when you try to call the string method startswith() 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 startswith() method. For example,

list_of_shapes = ['hexagon', 'pentagon', 'square', 'octagon']

for shape in list_of_shapes:

    if shape.startswith('hex'):

        print(f'Six-sided shape: {shape}')

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


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

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 ‘startswith’” tells us that the list object does not have the attribute startswith().

The startswith() method belongs to the string data type and returns True if a string ends with the specified prefix. 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 startswith() 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('startswith' in attributes)
False

The membership operation returns False for the list object.

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

string = "Python"

attributes = dir(string)

print('startswith' in attributes)
True

The membership operation returns True for the str object.

Example

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

list_of_shapes = ['hexagon', 'pentagon', 'square', 'octagon']

if list_of_shapes.startswith:
    
    print(f'Six-sided shape: {shape}')

In the above code, we define a list of strings containing the names of four different geometric shapes.

Next, we attempt to extract the shape from the list that starts with ‘hex‘ using the startswith() method in an if statement. Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [3], in <cell line: 3>()
      1 list_of_shapes = ['hexagon', 'pentagon', 'square', 'octagon']
----> 3 if list_of_shapes.startswith:
      5     print(f'Six-sided shape: {shape}')

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

The error occurs because we are trying to call the startswith() method on a list object. The startswith() 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 startswith() 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_shapes = ['hexagon', 'pentagon', 'square', 'octagon']

for shape in list_of_shapes:

    print(type(shape))

    if shape.startswith('hex'):

        print(f'Six-sided shape: {shape}')

Let’s run the code to see the result:

<class 'str'>
Six-sided shape: hexagon
<class 'str'>
<class 'str'>
<class 'str'>

We correctly used the startswith() method to find the shape starting with ‘hex‘, which in this case is hexagon.

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 shape that starts with ‘hex‘. We want to store these shapes in a new list.

list_of_shapes = ['hexagon', 'pentagon', 'square', 'octagon', 'hexagram']

six_side_or_point = [shape for shape in list_of_shapes if shape.startswith('hex')]

print('Six sided or pointed shapes:\n',six_side_or_point)

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

Six sided or pointed shapes:
 ['hexagon', 'hexagram']

We successfully extracted the shapes starting with ‘hex‘ and stored them in a new list.

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

list_of_shapes = ['hexagon', 'pentagon', 'square', 'octagon', 'hexagram']

print(list_of_shapes[0].startswith('hex'))

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

True

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 ‘endswith’

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 ✨