Skip to content
Advertisement

How to fix “AttributeError: ‘str’ object has no attribute ‘append'”

>>> myList[1]
'from form'
>>> myList[1].append(s)

Traceback (most recent call last):
  File "<pyshell#144>", line 1, in <module>
    myList[1].append(s)
AttributeError: 'str' object has no attribute 'append'
>>>

Why is myList[1] considered a 'str' object? mList[1] returns the first item in the list 'from form' but I cannot append to item 1 in the list myList.

I need to have a list of lists; so ‘from form’ should be a list. I did this:

>>> myList
[1, 'from form', [1, 2, 't']]
>>> s = myList[1]
>>> s
'from form'
>>> s = [myList[1]]
>>> s
['from form']
>>> myList[1] = s
>>> myList
[1, ['from form'], [1, 2, 't']]
>>> 

Advertisement

Answer

myList[1] is an element of myList and its type is string.

myList[1] is a string, you can not append to it. myList is a list, you should have been appending to it.

>>> myList = [1, 'from form', [1,2]]
>>> myList[1]
'from form'
>>> myList[2]
[1, 2]
>>> myList[2].append('t')
>>> myList
[1, 'from form', [1, 2, 't']]
>>> myList[1].append('t')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'
>>> 
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement