# [Tutor] 6 random numbers

Robert Sjoblom robert.sjoblom at gmail.com
Mon Oct 17 01:10:34 CEST 2011

>> hello all,
>> anyone know how i would go about printing 6 random numbers, i know i could copy and paste 6 times (which would work) but i was thinking about a while loop, ie. while lottery_numbers.count is <7.
>> Is it possible to code this? is it possible to count random variables? i am trying to keep the program as simple as possible, cheers
>>
>> any help would be welcome,
>>
>> import random
>> lottery_numbers=random.randrange(1,42)
>> print lottery_numbers
>>
>
> Following example may be useful:
> x = [random.randrange(1, 1+random.randrange(42) for _ in range(100)]
>
> http://docs.python.org/tutorial/datastructures.html

This wouldn't work because if you're making a lottery-type program,
you can't generate the same number again. A solution would be to check
if, say we stored the numbers in a list, len(set(numbers)) == 7 and if
it's not append another (random) number. This would be done until
len(set(numbers)) == 7. However, it's a bit tedious and the random
module offers a much better option:

import random
numbers = random.sample(range(1,42), 7)

random.sample returns k unique random elements from a population
sequence; in this case the population sequence is range(1, 42) (I
think python 2.x it'd be xrange()?) and the second argument would be
the number of elements we want.

>>>random.sample(range(1,42), 7)
[16, 29, 17, 2, 12, 36, 10]    #this list is in selection order!

--
best regards,
Robert S.