Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Using Python 2.7.3.1

I don't understand what the problem is with my coding! I get this error: AttributeError: 'list' object has no attribute 'split

This is my code:

myList = ['hello']

myList.split()
like image 463
sp3cro Avatar asked Nov 15 '14 03:11

sp3cro


People also ask

What does AttributeError list object has no attribute split mean?

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.

Does list have 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.

Why am I getting AttributeError Object has no attribute?

If you are getting an object that has no attribute error then the reason behind it is because your indentation is goofed, and you've mixed tabs and spaces.

How do you split a list of objects in Python?

To split the elements of a list in Python: Use a list comprehension to iterate over the list. On each iteration, call the split() method to split each string. Return the part of each string you want to keep.


2 Answers

You can simply do list(myList[0]) as below:

>>> myList = ['hello']
>>> myList=list(myList[0])
>>> myList
['h', 'e', 'l', 'l', 'o']

See documentation here

like image 182
user3885927 Avatar answered Sep 22 '22 13:09

user3885927


To achieve what you are looking for:

myList = ['hello']
result = [c for c in myList[0]] # a list comprehension

>>> print result
 ['h', 'e', 'l', 'l', 'o']

More info on list comprehensions: http://www.secnetix.de/olli/Python/list_comprehensions.hawk

Lists in python do not have a split method. split is a method of strings(str.split())

Example:

>>> s = "Hello, please split me"
>>> print s.split()
['Hello,', 'please', 'split', 'me']

By default, split splits on whitespace.

Check out more info: http://www.tutorialspoint.com/python/string_split.htm:

like image 33
Totem Avatar answered Sep 19 '22 13:09

Totem