. Advertisement .
..3..
. Advertisement .
..4..
I’m building a new program, but when I run it, an error pops up. The error displayed is as follows:
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
I have tried several workarounds, but they still do not get the desired results. If you have come across this situation and have a solution for the “typeerror: can only concatenate list (not “str”) to list” problem, pls let me know. Here is what I do:
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)
Thanks!
The cause: This error happens because you’re attempting to concatenate a list with a string, which is a Python error.
The solution: I think wwhat you want is to add and remove items from a list, your if/else block should look like this:
This is not how you add an item to your string. This:
This means you are trying to combine a string and a list. Use the
list.append()
method to add an item or two to a list.We hope this helps!
The cause: You get the warning message because you are attempting to concatenate a list with a string, but it is an invalid operation in Python.
Solution: We advise you to add a new item, and replace the line
newinv=inventory+str(add)
by this one as below:Then you need to add or remove items from a list. In this instance, your if/else should be:
It is not neccessary to create a new inventory whenever you add an item.