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

Rob Andrews rob@jam.rr.com
Tue, 24 Jul 2001 17:10:48 -0500


Take a look at the random and whrandom modules for a number of ways to go
about it. Here is an example, although probably a sloppy one, of the
variable someSpam being used to call a random item from the list spam.

PythonWin 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32.
Portions Copyright 1994-2001 Mark Hammond (MarkH@ActiveState.com) - see
'Help/About PythonWin' for further copyright information.
>>> import whrandom
>>> spam = ["parrot", "dead", "inquisition"]
>>> spamLength = (len(spam))-1
>>> randomSpam = whrandom.randint(0, spamLength)
>>> someSpam = spam[randomSpam]
>>> someSpam
'inquisition'

A peek at the whrandom documentation
(http://www.python.org/doc/current/lib/module-whrandom.html) might clarify
the steps quite a bit.

Rob

Your one-stop shop for newbie source code!
Useless Python: http://www.lowerstandard.com/python/

# -----Original Message-----
# From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
# steve
# Sent: Tuesday, July 24, 2001 4:48 PM
# To: tutor@python.org
# Subject: [Tutor] How to pull a random element from a list?
#
#
# 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!
#
# --
# Steve - Editor - www.formulaoneupdate.com
# --------------------------------
# "Trish, she has a paddle." - Jeff Hardy
#
# _______________________________________________
# Tutor maillist  -  Tutor@python.org
# http://mail.python.org/mailman/listinfo/tutor