Python attributeerror list object has no attribute split

Python AttributeError: ‘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 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’

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.

Читайте также:  Ubuntu update java runtime

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!

Share this:

Источник

Python attributeerror list object has no attribute split

Last updated: Jan 29, 2023
Reading time · 5 min

banner

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

The Python «AttributeError: ‘list’ object has no attribute ‘split'» occurs when we call the split() method on a list instead of a string.

To solve the error, call split() on a string, e.g. by accessing the list at a specific index or by iterating over the list.

attributeerror list object has no attribute split

Here is an example of how the error occurs.

Copied!
my_list = ['a-b', 'c-d'] # ⛔️ AttributeError: 'list' object has no attribute 'split' print(my_list.split('-'))

list object has no attribute split

We created a list with 2 elements and tried to call the split() method on the list which caused the error.

# Check if the variable is a string before calling split()

The str.split() method can only be called on strings.

You can use the isinstance() function to check if the variable stores a string before calling split() .

Copied!
my_str = 'bobby,hadz,com' if isinstance(my_str, str): new_list = my_str.split(',') print(new_list) # 👉️ ['bobby', 'hadz', 'com'] else: print('The variable is not a string') print(type(my_str))

check if variable is string before calling split

If your variable stores a list, you can:

  • Access the list at a specific index before calling split()
  • Iterate over the list and call the split() method on each string

# Access the list at an index before calling split()

One way to solve the error is to access the list at a specific index before calling split() .

Copied!
my_list = ['a-b', 'c-d'] result = my_list[0].split('-') print(result) # 👉️ ['a', 'b']

access list at index before calling split

We accessed the list element at index 0 and called the split() method on the string.

We split the string on each hyphen — in the example, but you can use any other delimiter.

Python indexes are zero-based, so the first item in a list has an index of 0 , and the last item has an index of -1 or len(a_list) — 1 .

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

Name Description
separator Split the string into substrings on each occurrence of the separator
maxsplit At most maxsplit splits are done (optional)

When no separator is passed to the str.split() method, it splits the input string on one or more whitespace characters.

The split() method splits the string on each occurrence of the provided separator into a list of substrings.

# Calling the split() method on each string in a list

If you need to call the split() method on each string in a list, use a for loop to iterate over the list.

Copied!
my_list = ['a-b', 'c-d'] new_list = [] for word in my_list: new_list.append(word.split('-')) result = word.split('-') print(result) # 👉️ ['a', 'b'] ['c', 'd'] print(new_list) # 👉️ [['a', 'b'], ['c', 'd']]

calling split on each string in list

We used a for loop to iterate over the list and called the split() method to split each string.

Alternatively, you can use a list comprehension.

Here is an example that splits each element in a list and keeps the first part.

Copied!
my_list = ['a-b', 'c-d'] # ✅ split each element in list and keep first part result_1 = [item.split('-', 1)[0] for item in my_list] print(result_1) # 👉️ ['a', 'c']

Here is an example that splits each element in a list into nested lists.

Copied!
my_list = ['a-b', 'c-d'] # ✅ split each element in list into nested lists result_2 = [item.split('-') for item in my_list] print(result_2) # 👉 [['a', 'b'], ['c', 'd']]

Here is an example that splits each element in a list and flattens the list.

Copied!
my_list = ['a-b', 'c-d'] # ✅ split each element in list and flatten list result_3 = [item.split('-') for item in my_list] result_3_flat = [item for l in result_3 for item in l] print(result_3_flat) # 👉️ ['a', 'b', 'c', 'd']

# Splitting a file on each line

Here is the example.txt text file that is used in the code samples below.

Copied!
name,age,country Alice,30,Austria Bobby,35,Belgium Carl,40,Canada

If you are reading from a file and need to split each line on the file, use a for loop.

Copied!
# ['name', 'age', 'country\n'] # ['Alice', '30', 'Austria\n'] # ['Bobby', '35', 'Belgium\n'] # ['Carl', '40', 'Canada'] with open('example.txt', 'r', encoding="utf-8") as f: for line in f: # 👇️ split line on each comma new_list = line.split(',') print(new_list)

python split each line in file

We opened a file called example.txt and used a for loop to iterate over the lines in the file.

If you need to read a file line by line, use the following code sample instead.

Copied!
with open('example.txt', 'r', encoding="utf-8") as f: for line in f: # name,age,country # Alice,30,Austria # Bobby,35,Belgium # Carl,40,Canada print(line.rstrip())

read each line in a file

The code sample iterates over the file, reads each line and uses the str.rstrip() method to remove the trailing newline characters.

If you only need to print the Nth element of each line, use the split() method and access the result at an index.

Copied!
with open('example.txt', 'r', encoding="utf-8") as f: for line in f: new_list = line.split(',') # name # Alice # Bobby # Carl print(new_list[0])

only access first column of file

We split each line in the list and accessed the new list at index 0 to only get the first column.

# Split the characters of a list element without a separator

If you need to split the characters of a list element without a separator, use a list comprehension.

Copied!
my_list = ['hello'] result = [char for char in my_list[0]] print(result) # 👉️ ['h', 'e', 'l', 'l', 'o']

split characters of list element without separator

# Track down where the variable got assigned a list

The error occurs when we try to call the split() method on a list instead of a string.

To solve the error, you either have to correct the assignment of the variable and make sure to call split() on a string, or call split() on an element in the list that is of type string .

You can either access the list at a specific index, e.g. my_list[0] or use a for loop to iterate over the list if you have to call split() on each element.

You can view all the attributes an object has by using the dir() function.

Copied!
my_list = ['a', 'b', 'c'] # 👉️ [. 'append', 'clear', 'copy', 'count', 'extend', 'index', # 'insert', 'pop', 'remove', 'reverse', 'sort' . ] print(dir(my_list))

If you pass a class to the dir() function, it returns a list of names of the class’s attributes, and recursively of the attributes of its bases.

If you try to access any attribute that is not in this list, you would get the «AttributeError: list object has no attribute» error.

Since split() is not a method implemented by lists, the error is caused.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью