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

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
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.

main.py
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.

The split() method is string-specific, so we have to call it on a string, and not on a list object.

# 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().

main.py
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().

main.py
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:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt 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.

main.py
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.

main.py
my_list = ['a-b', 'c-d'] # โœ… Split each element in the list and keep the 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.

main.py
my_list = ['a-b', 'c-d'] # โœ… Split each element in the 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.

main.py
my_list = ['a-b', 'c-d'] # โœ… Split each element in the list and flatten the 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.

example.txt
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.

main.py
# ['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 the 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.

On each iteration, we used the split() method to split the line on each occurrence of a comma.

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

main.py
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.

main.py
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.

main.py
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.

main.py
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 will 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.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev