convert a list to a string
Jeff Epler
jepler at unpythonic.net
Thu Jan 8 22:57:47 EST 2004
On Thu, Jan 08, 2004 at 10:31:16PM -0500, Bart Nessux wrote:
> How does randint and sample differ? I was under the impression that
> sample was more random.
sample is useful when you want to choose several items from the
population. The degenerate case
random.sample(range(100), 1)
is equivalent to
[random.choice(range(100))]
is equivalent to
[random.randrange(100)]
here's where sample is useful: Pick a TLA, but don't repeat any letters:
>>> "".join(random.sample(string.uppercase, 3))
'CLA'
You can't sample more than your whole population:
>>> "".join(random.sample(string.uppercase, 28))
ValueError: sample larger than population
And here's another way to take a random permutation of the alphabet:
>>> "".join(random.sample(string.uppercase, 26))
'STFVCQHDLOUNERPYIMABGJXKZW'
No letters are repeated, unlike with random.choice:
>>> "".join([random.choice(string.uppercase) for i in
>>> range(26)])
'ZMXYCNLDCQAIYTAVPPTSGABNVU'
(the odds of *not* having a duplicate letter here are quite small,
though I don't know offhand just how small--maybe 26!/(26**25)?)
Jeff
More information about the Python-list
mailing list