A random word from one of two lists

Richard Damon Richard at Damon-Family.org
Fri Jan 1 18:12:57 EST 2021


On 1/1/21 5:58 PM, Bischoop wrote:
> I have two lists *animal* and *fruit* and I try to get a random variable
> animal or fruit and then random word from that list.
> I thought that dictionary(*words*) could help me but no succes, the only way I've
> done partially what was with list *kinds* and by using two times
> random.choice. However print(kind) return me a list not a variable:
> animal or fruit so now I'm kinda confuse if I can achieve that.
>
>
>
> import random
> animal = ['koala', 'kangaroo']
> fruit = ['banana', 'apple']
> kinds = [animal,fruit]
> words = {'animals': animal, 'fruits': fruit}
>
>
> kind = random.choice(kinds)
> print(kind)
> word = random.choice(kind)
> print(word)
> #output:
> ['kolala', 'kangaroo']
> kangaroo
>
> --
> Thanks

random.choice doesn't return 'a variable' but an object. Which is the
same object that one of the variables that you used.

IF you wanted to use words, then you could have made kinds = {'animals',
'fruits'} and then looked up the list in words, but that is really just
more work (unless you want to know which list it came from)

Note that 'animals' isn't a variable, but a string value.

-- 
Richard Damon



More information about the Python-list mailing list