>>> 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']] >>>
The Python "AttributeError: 'str' object has no attribute" occurs when we try to access an attribute that doesn't exist on string objects. To solve the error, make sure the value is of the expected type before accessing the 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. Run the script with python -tt to verify.
The Python "AttributeError: 'int' object has no attribute 'append'" occurs when we call the append() method on an integer. To solve the error, make sure the value you are calling append on is of type list . Here is an example of how the error occurs. main.py. Copied!
Solution for AttributeError Errors and exceptions in Python can be handled using exception handling i.e. by using try and except in Python. Example: Consider the above class example, we want to do something else rather than printing the traceback Whenever an AttributeError is raised.
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' >>>
If you want to append a value to myList
, use myList.append(s)
.
Strings are immutable -- you can't append to them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With