Solve attributeerror: ‘list’ object has no attribute ‘split’ in Python

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']]