List object has no attribute split как исправить

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

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.


Table of contents

  • AttributeError: ‘list’ object has no attribute ‘split’
  • Example #1: Splitting a List of Strings
    • Solution
  • Example #2: Splitting Lines from a CSV File
    • Solution
  • Summary

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.99n', 'pepperoni, £8.99n', 'four cheeses, £10.99n', 'funghi, £8.99n']

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:

  • How to Solve Python AttributeError: ‘int’ object has no attribute ‘split’
  • How to Solve Python AttributeError: ‘list’ object has no attribute ‘strip’
  • How to Solve Python AttributeError: ‘_csv.reader’ object has no attribute ‘next’

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!

Posted on Jan 03, 2023


Python shows AttributeError: ’list’ object has no attribute ‘split’ when you try to use the split() method on a list object instead of a string.

To fix this error, you need to make sure you are calling the split() method on a string object and not a list. Read this article to learn more.

The split() method is a string method that is used to divide a string into a list of substrings based on a specified delimiter.

When you call this method on a list object as shown below:

words = ['hello', 'world']
words.split()

You’ll receive the following error response from Python:

To resolve this error, you need to make sure you are calling the split() method on a string.

You can use an if statement to check if your variable contains a string type value like this:

words = "hello world"

if type(words) is str:
    new_list = words.split()
    print(new_list)
else:
    print("Variable is not a string")

In the example above, the type() function is called to check on the type of the words variable.

When it’s a string, then the split() method is called and the new_list variable is printed. Otherwise, print “Variable is not a string” as the output.

If you have a list of string values that you want to split into a new list, you have two options:

  1. Access the list element at a specific index using square brackets [] notation
  2. Use a for loop to iterate over the values of your list

Let’s see how both options above can be done.

Access a list element with [] notation

Suppose you have a list of names and numbers as shown below:

users = ["Nathan:92", "Jane:42", "Leo:29"]

Suppose you want to split the values of the users list above as their own list.

One way to do it is to access the individual string values and split them like this:

users = ["Nathan:92", "Jane:42", "Leo:29"]

new_list = users[0].split(":")

print(new_list)  # ['Nathan', '92']

As you can see, calling the split() method on a string element contained in a list works fine.

Note that the split() method has an optional parameter called delimiter, which specifies the character or string that is used to split the string.

By default, the delimiter is any whitespace character (such as a space, tab, or newline).

The code above uses the colon : as the delimiter, so you need to pass it as an argument to split()

Using a for loop to iterate over a list and split the elements

Next, you can use a for loop to iterate over the list and split each value.

You can print the result as follows:

users = ["Nathan:92", "Jane:42", "Leo:29"]

for user in users:
    result = user.split(":")
    print(result)

The code above produces the following output:

['Nathan', '92']
['Jane', '42']
['Leo', '29']

Printing the content of a file with split()

Finally, this error commonly occurs when you try to print the content of a file you opened in Python.

Suppose you have a users.txt file with the following content:

EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL
198,Donald,OConnell,doconnel@mail.com
199,Douglas,Grant,dgrant@mail.com
200,Jennifer,Whalen,jwhalen@mail.com
201,Michael,Hartl,mhartl@mail.com

Next, you try to read each line of the file using the open() and readlines() functions like this:

readfile = open("users.txt", "r")
readlines = readfile.readlines()

result = readlines.split(",")

The readlines() method returns a list containing each line in the file as a string.

When you try to split a list, Python responds with the AttributeError message:

Traceback (most recent call last):
  File "script.py", line 10, in <module>
    result = readlines.split(",")
             ^^^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'split'

To resolve this error, you need to call split() on each line in the readlines object.

Use the for loop to help you as shown below:

readfile = open("users.txt", "r")
readlines = readfile.readlines()

for line in readlines:
    result = line.split(',')
    print(result)

The output of the code above will be:

['EMPLOYEE_ID', 'FIRST_NAME', 'LAST_NAME', 'EMAILn']
['198', 'Donald', 'OConnell', 'doconnel@mail.comn']
['199', 'Douglas', 'Grant', 'dgrant@mail.comn']
['200', 'Jennifer', 'Whalen', 'jwhalen@mail.comn']
['201', 'Michael', 'Hartl', 'mhartl@mail.com']

You can manipulate the file content using Python as needed.

For example, you can print only the FIRST_NAME detail from the file using print(result[1]):

for line in readlines:
    result = line.split(',')
    print(result[1])

Output:

FIRST_NAME
Donald
Douglas
Jennifer
Michael

Conclusion

To conclude, the Python “AttributeError: ’list’ object has no attribute ‘split’” occurs when you try to call the split() method on a list.

The split() method is available only for strings, so you need to make sure you are actually calling the method on a string.

When you need to split elements inside a list, you can use the for loop to iterate over the list and call the split() method on the string values inside it.

Python lists cannot be divided into separate lists based on characters that appear in the values of a list. This is unlike strings which values can be separated into a list.

If you try to use the split() method on a list, you get the error “attributeerror: ‘list’ object has no attribute ‘split’”.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

In this guide, we talk about what this error means and why you may find it in your code. We also walk through an example scenario to help you figure out how to solve this error.

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

This error tells us we are trying to use a function that is not available on lists.

The split() method splits a string into a list. The string is broken up at every point where a separator character appears. For instance, you can divide a string into a list which contains all values that appear after a comma and a space (“, ”):

cakes = "Cheese Scone, Cherry Scone, Fruit Scone"
cake_list = cakes.split(", ")

print(cake_list)

Our code splits the “cakes” string between the places where a comma followed by a space is present. These values are then added to the list called “cake_list”. Our code returns:

['Cheese Scone', 'Cherry Scone', 'Fruit Scone']

The split() operation only works on strings.

An Example Scenario

We have a CSV file which contains information about cakes sold at a tea house. We want to print out the name of each cake to the Python shell so that customers can choose what they want to have with their drink.

Our CSV file looks like this:

Cheese Scone, $1.30, Vegetarian
Toasted Teacake, $1.50, Vegetarian
Fruit Bread, $1.40, Vegetarian

Our file contains three entries: one for cheese scones, one for toasted teacakes, and one for fruit bread. We read this file into our program so that we an access our values:

with open("cakes.csv", "r") as file:
	cakes = file.readlines()

	cake_names = cakes.split(", ")[0]
	print(cake_names)

This program reads the “cakes.csv” file. It then uses the split() method to split up the values in each record so that we can access the names of each cake.

We use the [0] indexing syntax to access the first item in a record. This corresponds to the name of a cake.

Let’s run our code and see what happens:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
	cake_names = cakes.split(", ")[0]
AttributeError: 'list' object has no attribute 'split'

Our code, as expected, returns an error.

The Solution

We try to use the split() method on a list. Let’s print out the contents of “cakes” to the console:

with open("cakes.csv", "r") as file:
	cakes = file.readlines()
	print(cakes)

Our code returns:

['Cheese Scone, $1.30, Vegetariann', 'Toasted Teacake, $1.50, Vegetariann', 'Fruit Bread, $1.40, Vegetariann']

Our code cannot separate a list into multiple lists using split(). This is because lists are already separated by commas. Instead, we should use the split() method on each item in our list.

We can do this by using a for loop to iterate over every line in the “cakes.csv” file:

with open("cakes.csv", "r") as file:
	cakes = file.readlines()

	for c in cakes:
		split_lines = c.split(", ")
		print(split_lines[0])

We initialized a for loop that goes through every line in the “cakes” variable. We use the split() method to divide each string value in the list by the “, ”string pattern. This means the cake names, prices, and vegetarian status are to be divided into a list.

On the last line of our code, we use split_lines[0] to print out the first item in each new list. This is equal to the name of each cake. Let’s try to run our code:

Cheese Scone
Toasted Teacake
Fruit Bread

Our code successfully prints out a list of cakes. This is because we did not separate a list. We use split() to separate all the items in each string that appears in our list.

Conclusion

The “attributeerror: ‘list’ object has no attribute ‘split’” error is raised when you try to divide a list into multiple lists using the split() method.

You solve this error by ensuring you only use split() on a string. If you read a file into a program, make sure you use split() on each individual line in the file, rather than a list of all the lines.

Now you’re ready to solve this common Python error like a pro!

Понравилась статья? Поделить с друзьями:
  • List object has no attribute replace как исправить
  • List object cannot be interpreted as an integer как исправить
  • List is empty egov mobile ошибка
  • List indices must be integers or slices not str как исправить
  • List indices must be integers or slices not str python ошибка