[Tutor] Trying to access a random value in a list
Steven D'Aprano
steve at pearwood.info
Sat Jan 14 04:18:09 CET 2012
On 13/01/12 10:56, Nick W wrote:
> first problem: easy fix just remember that len() returns the actual
> number of items in the list but that list is indexed starting at 0 so
> just replace your line of
> pick = len(names)
> with:
> pick = len(names) - 1
Another good trick for choosing a random value from a list is to avoid picking
a number first and just ask for a random choice:
>>> import random
>>> L = ['spam', 'ham', 'cheese', 'eggs']
>>> random.choice(L)
'cheese'
> and for problem #2:
> just use string formating... like for example instead of:
> print (names[win_number], " is the winner!")
> try something along the lines of:
> print("{} is a winner".format(names[win_number]))
Apart from being longer and harder, is there an advantage to the second form?
:)
A third alternative is:
print("%s is a winner" % names[win_number])
In any case, none of these solve the actual problem. The original poster is
talking about printing the list of names:
print (names, "have been entered.")
which prints an actual LIST, so you get (e.g.):
['fred', 'barney']
instead of:
fred barney
The easy way to fix that is to use:
print (" ".join(names), "have been entered.")
--
Steven
More information about the Tutor
mailing list