Home > Net >  How to get around 'AttributeError: 'str' object has no attribute 'append'&#
How to get around 'AttributeError: 'str' object has no attribute 'append'&#

Time:06-09

In this practice program in which the user is asked to remove some subjects from a list of subjects, and at the end display the modified list. I'm getting:

'AttributeError: 'str' object has no attribute 'append'' error on line 8 [to_remove = to_remove.append(next)--- this line]

list1 = ["science", "maths", "english", "social", "economics", "pe"]
print(list1)
to_remove = []
to_remove = input("Enter the subject you like to remove: ")
query = input("Do you like to remove more? ")
while query != "no":
    next = input("Enter the subject name: ")
    to_remove = to_remove.append(next)
    query = input("Would you like to remove more? ")
print("Thank you\n")

for i in to_remove:
    list1.remove(i)
print("Here is your modified list:\n")
print(list1)

CodePudding user response:

The name of the list and the input variable were the same. So, there was a conflict. You were trying to access the append method of the input string. Also, the first input you enter was never stored in a list, so fixed that too

list1 = ["science", "maths", "english", "social", "economics", "pe"]
print(list1)
to_remove_list = [] #Changed the name here
to_remove = input("Enter the subject you like to remove: ")
to_remove_list.append(to_remove) # Your first element is now appending to list
query = input("Do you like to remove more? ")
while query != "no":
    next = input("Enter the subject name: ")
    to_remove = to_remove_list.append(next)
    query = input("Would you like to remove more? ")
print("Thank you\n")
for i in to_remove_list:
    list1.remove(i)
print("Here is your modified list:\n")
print(list1)

CodePudding user response:

Based on the comments and answers, the issue was I declared to_remove as a list and later tried to store a string input in it instead. So when I tried to append, I was trying to append to a string [which is not possible], thus the error. Here's the code that fixed the error.

list1 = ["science", "maths", "english", "social", "economics", "pe"]
print(list1)
to_remove = []
to_remove.append(input("Enter the subject you like to remove: "))
query = input("Do you like to remove more? ")
while query != "no":
    to_remove.append(input("Enter the subject name: "))
    query = input("Would you like to remove more? ")
print("Thank you\n")
for i in to_remove:
    list1.remove(i)
print("Here is your modified list:\n")
print(list1)
  • Related