TypeError: can only concatenation list (not "str") to list

I am trying to make an inventory program for use in an RPG game. The program should be able to add and remove things and add them to the list. This is what I still have:

inventory=["sword","potion","armour","bow"] print(inventory) print("\ncommands: use (remove) and pickup (add)") selection=input("choose a command [use/pickup]") if selection=="use": print(inventory) remove=input("What do you want to use? ") inventory.remove(remove) print(inventory) elif selection=="pickup": print(inventory) add=input("What do you want to pickup? ") newinv=inventory+str(add) print(newinv) 

When I run this and try to select something, I get this error:

 Traceback (most recent call last): File "H:/Year 10/Computing/A453/Python Programs/inventory.py", line 15, in <module> newinv=inventory+str(add) TypeError: can only concatenate list (not "str") to list 

Does anyone have a fix for this, we will be very grateful

+8
python
source share
2 answers

I think you want to add a new item to your list, so you change the line newinv=inventory+str(add) to this:

 newinv = inventory.append(add) 

Now you are trying to combine a list with a string, which is an invalid operation in Python.

However, I think you want to add and remove items from the list, in which case your if / else block should be:

 if selection=="use": print(inventory) remove=input("What do you want to use? ") inventory.remove(remove) print(inventory) elif selection=="pickup": print(inventory) add=input("What do you want to pickup? ") inventory.append(add) print(inventory) 

You do not need to create a new inventory list every time you add a new item.

+9
source share

This is not like adding an item to a string. It:

 newinv=inventory+str(add) 

means you are trying to combine a list and a string. To add an item to the list, use the list.append() method.

 newinv = inventory.append(add) #newinv is the old inventory, with a new item. 

Or, to simplify newinv bit, just drop the newinv list.

 inventory.append(add) #adds a new item to inventory print(inventory) #prints the new inventory 

Hope this helps!

0
source share

All Articles