shopping_list = ['food','drinks']
shopping_list.pop(0)
print(shopping_list)
new_shopping_list = shopping_list.pop(0)
new_shopping_list.insert(0,'fruits')
print(new_shopping_list)
Hi this is my first question on stack overflow, have a feeling I am going to use this site a lot more in future :/. Just learnt about lists today, and I read that popped elements of a list can still be operated on despite being removed so I tested it out with the code above, but I had an attribute error pop up. Why is this and how can I fix it?
Here is the error:
AttributeError: 'str' object has no attribute 'insert'
Thanks in advance whoever answers :)
CodePudding user response:
You are storing string value in new_shopping_list. The new_shopping_list variable stores data which are pop from list not the whole list. You can use this snippet.
shopping_list = ['food','drinks']
shopping_list.pop(0)
print(shopping_list)
shopping_list.pop(0)
shopping_list.insert(0,'fruits')
print(shopping_list)
CodePudding user response:
If you check type of new_shopping_list using type(new_shopping_list)
. it is a str
. It does not have any attribute 'insert'.
I think you wanted to insert in original list shopping_list
CodePudding user response:
If you delete : New_shopping_list=shopping_list.pop(0) And write: Shopping_list.insert(0,'friuts') Print(shopping_list) Will countinue easily without erorrs.