[Tutor] Re: Random numbers

Anna Ravenscroft anna at aleax.it
Fri Oct 10 15:27:27 EDT 2003


On Friday 10 October 2003 09:09 pm, Abel Daniel wrote:
> UCT Student - DLLBIA001 <DLLBIA001 at mail.uct.ac.za> writes:
> > i was just wandring if you could not help me to generate 25 random
> > numbers in the range of 0 to 24 without any number repeating.
>
> Just a note: in this case you aren't 'generating random numbers' but
> 'shuffling numbers'.
>
> Abel Daniel
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

Okay - OP might want to look into the new "sample" function in module random.

>>> import random
>>> random.sample(range(25), 25)
[20, 8, 14, 4, 13, 10, 1, 21, 19, 7, 6, 23, 22, 16, 5, 17, 15, 2, 18, 12, 24, 
3, 0, 9, 11]
>>>

If you only want, say, 10 of the values from your range, you can do this:
>>> random.sample(range(25), 10)
[16, 15, 21, 24, 14, 17, 0, 7, 9, 11]
>>>

If you don't care about repetition in your samples, then just use 
randrange...:
To get one random number at a time:
>>> random.randrange(25)
11

Or, to get a list of them, use a list comprehension:

>>> [random.randrange(25) for i in range(10)]
[2, 21, 8, 3, 4, 23, 1, 21, 13, 11]
>>> [random.randrange(25) for i in range(10)]
[8, 6, 1, 21, 9, 24, 14, 5, 12, 3]
>>> [random.randrange(25) for i in range(10)]
[22, 19, 20, 20, 2, 13, 7, 3, 11, 7]
>>>

HTH
Anna Ravenscroft
-- 
There is a type 3 error in which your mind goes totally blank whenever you try 
to remember which is which of type 1 and type 2.
                                                 -Richard Dawkins




More information about the Tutor mailing list