Python AttributeError: ‘list’ object has no attribute ‘split’

by | Programming, Python, Tips

In Python, the list data structure stores elements in sequential order. To convert a string to a list object, we can use the split() function on the string, giving us a list of strings. However, we cannot apply the split() function to a list. If you try to use the split() method on a list, you will raise the error “AttributeError: ‘list’ object has no attribute ‘split’”.

This tutorial will go into detail on the error definition. We will go through an example that causes the error and how to solve it.


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

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 ‘split’” tells us that the list object we are handling does not have the split attribute. We will raise this error if we try to call the split() method or split property on a list object. split() is a string method, which splits a string into a list of strings using a separating character. We pass a separating character to the split() method when we call it.

Example #1: Splitting a List of Strings

Let’s look at using the split() method on a sentence.

# Define string

sentence = "Learning new things is fun"

# Convert the string to a list using split

words = sentence.split()

print(words)
['Learning', 'new', 'things', 'is', 'fun']

The default delimiter for the split() function is space ” “. Let’s look at what happens when we try to split a list of sentences using the same method:

# Define list of sentences

sentences = ["Learning new things is fun", "I agree"]

print(sentences.split())
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
1 print(sentences.split())

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

Solution

To solve the above example, we need to iterate over the strings in the list to get individual strings; then, we can call the split() function

# Define sentence list

sentences = ["Learning new things is fun", "I agree"]

# Iterate over items in list

for sentence in sentences:
    
    # Split sentence using white space

    words = sentence.split()
    
    print(words)

print(sentences.split())
['Learning', 'new', 'things', 'is', 'fun']

['I', 'agree']

Example #2: Splitting Lines from a CSV File

Let’s look at an example of a CSV file containing the names of pizzas sold at a pizzeria and their prices. We will write a program that reads this menu and prints out the selection for customers entering the pizzeria. Our CSV file, called pizzas.csv, will have the following contents:

margherita, £7.99

pepperoni, £8.99

four cheeses, £10.99

funghi, £8.99

The code will read the file into our program so that we can print the pizza names:

# Read CSV file 

with open("pizzas.csv", "r") as f:
   
    pizza = f.readlines()

    # Try to split list using comma 

    pizza_names = pizza.split(",")[0]
   
    print(pizza_names)

The indexing syntax [0] access the first item in a list, which would be the name of the pizza. If we try to run the code, we get the following output:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
      1 with open("pizzas.csv", "r") as f:
      2     pizza = f.readlines()
----≻ 3     pizza_names = pizza.split(",")[0]
      4     print(pizza_names)
      5 

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

We raise the error because we called the split() function on a list. If we print the pizza object, we will return a list.

# Read CSV file 

with open("pizzas.csv", "r") as f:
   
   pizza = f.readlines()
   
   print(pizza)
['margherita, £7.99\n', 'pepperoni, £8.99\n', 'four cheeses, £10.99\n', 'funghi, £8.99\n']

Each element in the list has the newline character \n to signify that each element is on a new line in the CSV file. We cannot separate a list into multiple lists using the split() function. We need to iterate over the strings in the list and then use the split() method on each string.

Solution

To solve the above example, we can use a for loop to iterate over every line in the pizzas.csv file:

# Read CSV file 

with open("pizzas.csv", "r") as f:
   
    pizza = f.readlines()

    # Iterate over lines

    for p in pizzas:

        # Split each item
    
        pizza_details = p.split(",")

        print(pizza_details[0])

The for loop goes through every line in the pizzas variable. The split() function divides each string value by the , delimiter. Therefore the first element is the pizza name and the second element is the price. We can access the first element using the 0th index, pizza_details[0] and print it out to the console. The result of running the code is as follows:

margherita

pepperoni

four cheeses

funghi

We have a list of delicious pizzas to choose from! This works because we did not try to separate a list, we use split() on the items of the list which are of string type.

Summary

Congratulations on reading to the end of this tutorial! The error “AttributeError: ‘list’ object has no attribute ‘split’” occurs when you try to use the split() function to divide a list into multiple lists. The split() method is an attribute of the string class.

If you want to use split(), ensure that you iterate over the items in the list of strings rather than using split on the entire list. If you are reading a file into a program, use split() on each line in the file by defining a for loop over the lines in the file.

To learn more about getting substrings from strings, go to the article titled “How to Get a Substring From a String in Python“.

For further reading on AttributeErrors, go to the articles:

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 ✨