I think you’ve actually got a wider confusion here.
The initial error is that you’re trying to call split
on the whole list of lines, and you can’t split
a list of strings, only a string. So, you need to split
each line, not the whole thing.
And then you’re doing for points in Type
, and expecting each such points
to give you a new x
and y
. But that isn’t going to happen. Types
is just two values, x
and y
, so first points
will be x
, and then points will be y
, and then you’ll be done. So, again, you need to loop over each line and get the x
and y
values from each line, not loop over a single Types
from a single line.
So, everything has to go inside a loop over every line in the file, and do the split
into x
and y
once for each line. Like this:
def getQuakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
for line in readfile:
Type = line.split(",")
x = Type[1]
y = Type[2]
print(x,y)
getQuakeData()
As a side note, you really should close
the file, ideally with a with
statement, but I’ll get to that at the end.
Interestingly, the problem here isn’t that you’re being too much of a newbie, but that you’re trying to solve the problem in the same abstract way an expert would, and just don’t know the details yet. This is completely doable; you just have to be explicit about mapping the functionality, rather than just doing it implicitly. Something like this:
def getQuakeData():
filename = input("Please enter the quake file: ")
readfile = open(filename, "r")
readlines = readfile.readlines()
Types = [line.split(",") for line in readlines]
xs = [Type[1] for Type in Types]
ys = [Type[2] for Type in Types]
for x, y in zip(xs, ys):
print(x,y)
getQuakeData()
Or, a better way to write that might be:
def getQuakeData():
filename = input("Please enter the quake file: ")
# Use with to make sure the file gets closed
with open(filename, "r") as readfile:
# no need for readlines; the file is already an iterable of lines
# also, using generator expressions means no extra copies
types = (line.split(",") for line in readfile)
# iterate tuples, instead of two separate iterables, so no need for zip
xys = ((type[1], type[2]) for type in types)
for x, y in xys:
print(x,y)
getQuakeData()
Finally, you may want to take a look at NumPy and Pandas, libraries which do give you a way to implicitly map functionality over a whole array or frame of data almost the same way you were trying to.
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:
- Access the list element at a specific index using square brackets
[]
notation - 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.
There are instances in which you might need to divide Python lists into smaller chunks for simpler processing or just to focus your data analysis work on relevant data. A very prevalent case for this is when working with csv (Comma Separated Values) files.
In today’s short Python programming tutorial we will learn how to troubleshoot a very common mistake we do when beginning coding Python : we try to use the split() and splitlines() methods, which are basically string methods, on lists.
Fixing the ‘list’ object has no attribute ‘split’ error
Let’s quickly create a list from a string – feel free to follow along by copying this code into your favorite development editor:
# define a Python string containing multiple elements
prog_lang = "Python,R,C#,Scala"
# create a list
prog_lang_lst = prog_lang.split(',')
We have used the split() method on our string to create our Python list:
print( prog_lang_lst)
This will return the following list:
['Python', 'R', 'C#', 'Scala']
Can’t divide Python lists using split
If we try to use the split() method to divide the list we get the error:
# this will result in an error
prog_lang_lst.split(',')
Here’s the exception that will be thrown:
AttributeError: 'list' object has no attribute 'split'
Ways to fix our split AttributeError
We can easily split our lists in a few simple ways, feel free to use whicever works for you.
Print our list elements
Our list is an iterable, so we can easily loop into it and print its elements as strings:
for e in prog_lang_lst:
print (e)
The result will be:
Python
R
C#
Scala
Split list into multiple lists
We loop through the list and divide its elements according to the separating character – a comma in our case:
for e in prog_lang_lst:
print (e.split(','))
Here’s the output:
['Python']
['R']
['C#']
['Scala']
Split and join the list elements to a string
We can easily use the join method to join the list elements into a string
print(', '.join(prog_lang_lst))
This will render the following result:
Python, R, C#, Scala
Split into a list of lists
We can use a list comprehension to split our list into a list of lists as shown below:
prog_lang_l_lst = [e.split(',') for e in prog_lang_lst]
print(prog_lang_l_lst)
Here’s the output
[['Python'], ['R'], ['C#'], ['Scala']]
I am having problems with this bit of code
import csv
temp = open("townsfile.csv", "r")
towns = temp.read()
temp.close()
print(towns)
eachTown = towns.split("n")
print (eachTown)
record = eachTown.split(",")
for line in eachTown:
record = eachItem.split(",")
print(record)
newlist=[]
newlist.append(record)
newlist=[]
for eachItem in eachTown:
record = eachItem.split(",")
newlist.append(record)
print(newlist)
It returns this error
Traceback (most recent call last):
File "N:/Python practice/towns.py", line 10, in <module>
record = eachTown.split(",")
AttributeError: 'list' object has no attribute 'split'
Can anyone help me with this
Martin Evans
45.4k17 gold badges79 silver badges94 bronze badges
asked Oct 10, 2017 at 7:40
5
The csv
module gives you this text parsing functionality, you do not need to do it yourself.
import csv
with open("townsfile.csv", "r") as f:
reader = csv.reader(f, delimiter=',')
towns = list(reader)
print(towns)
The problem you have is that list.split()
does not exist, you are trying to use str.split()
but you already split it into a list
of str
s. You would need to do it for every str
in the list.
answered Oct 10, 2017 at 7:53
AdirioAdirio
4,9801 gold badge14 silver badges26 bronze badges
2
eachTown = towns.split("n")
This code return list. List don’t have attribute split. You should replace
record = eachTown.split(",")
like this
records = [rec.split(",") for rec in eachTown]
But better if you start using module csv for read this file.
answered Oct 10, 2017 at 7:50
Zheka KovalZheka Koval
5254 silver badges10 bronze badges