[Tutor] How to pull a random element from a list?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 24 Jul 2001 20:32:21 -0700 (PDT)


On Tue, 24 Jul 2001 sill@optonline.net wrote:

> On Tue, Jul 24, 2001 at 03:47:58PM -0600, steve wrote:
> > Greetings
> > 
> > I'm trying to figure out how the heck to pull an element from a list or 
> > dictionary at random. I have a list of words and need to be able to pull one 
> > at random. (Yet to decide if a list is the right way to do it. Thoughts?)
> > 

> > I've messed around with my limited knowledge, but haven't been able to
> > figure out how to do it. I was going to use a random number generator
> > to pick which element to retrieve.

> > 
> > I am at your mercy oh mighty Pythonistas! HELP!
> 
> >>> l = ['word1','word2','blah','drah']
> >>> import random
> >>> random.choice(l)
> 'word2'

And for a dictionary, it depends if you want to choose a random key or
value:

###
>>> mydict = { 'a' : 'apple',
...            'b' : 'bear',
...            'c' : 'canada' }
>>> import random
>>> random.choice(mydict.keys())
'a'
>>> random.choice(mydict.keys())
'b'
>>> random.choice(mydict.values())
'bear'
>>> random.choice(mydict.values())
'apple'
>>> random.choice(mydict.values())
'bear'
>>> random.choice(mydict.values())
'bear'
>>> random.choice(mydict.values())
'apple'
>>> random.choice(mydict.values())
'canada'
###

That took a while to get Canada... I felt like Rosencranz and Guildenstern
for a moment.

Good luck!