why doesn't this work? how do i refer to a list... inside a list

Viewed 37

I am trying to make a randomly generated fantasy story, and it is not letting me refer to a list inside a list. line 36 is the bottom line of the code shown. I've looked it up and did what it said, but it isn't working! maybe because it was for printing text and a list, not making a list with a list inside it, and I don't understand the error message...

 itemA = ["letter ", "scroll ", "message "]
 specialPlace = ["waterfall.'", "rock pile.'"]
 
 events = [f"a {mysticalCreature[randint(0,8)]} comes up to you and gives you a {itemA[randint(0,2)]} saying, 'come to the " + specialPlace + ", so you thank them and walk away."]```



Traceback (most recent call last):
File "main.py", line 36, in <module>
 events = [f"a {mysticalCreature[randint(0,8)]} comes up to you and gives you a {itemA[randint(0,2)]} saying, 'come to the " + specialPlace + ", so you thank them and walk away."]
TypeError: can only concatenate str (not "list") to str
2 Answers

specialMessage is a list, and you're trying to use + to concatenate it with strings. If you want to choose a random value from it to put there, replace it with random.choice(specialMessage). Otherwise, you need to determine which string in that list you want to use in some other way.

You should probably be using random.choice in the other cases too; as written, if you change the length of any list you have to manually adjust the associated randint calls, while random.choice(mysticalCreature) gets the same result without hard-coding in any magic numbers.

import random

mysticalCreature = ["Fairy ", "Unicorn ", "Vampire (a fairy one) ", "Sasquatch ", "Dragon ", "Pheonix ", "Griffin ", "Satyr ", "Centaur " ]
itemA = ["letter ", "scroll ", "message "]
specialPlace = ["waterfall.'", "rock pile.'"]

events = [f"a {mysticalCreature[random.randint(0,8)]} comes up to you and gives you a {itemA[random.randint(0,2)]} saying, 'come to the " + specialPlace[random.randint(0,1)] + ", so you thank them and walk away."]
print(events)
Related