[Tutor] What does "random" in shuffle( x[, random]) do?

Kent Johnson kent37 at tds.net
Sun Sep 3 13:43:41 CEST 2006


Dick Moores wrote:
> http://docs.python.org/lib/module-random.html says,
>
> "shuffle( x[, random])
> Shuffle the sequence x in place. The optional argument random is a 0-argument 
> function returning a random float in [0.0, 1.0); by default, this is the 
> function random()."
>
>  >>> from random import shuffle, random
>  >>> lst = ["a", "b", "c", "d"]
>  >>> shuffle(lst)
>  >>> lst
> ['c', 'b', 'd', 'a']
>  >>> shuffle(lst, random)
>  >>> lst
> ['d', 'c', 'b', 'a']
>  >>>
>
> I can't see that shuffle(a) is any different from shuffle(a, random). Is it? And 
> how?
>   
The docs say that shuffle(a) *is* the same as shuffle(a, random). If you 
don't supply a second argument, the function random() is used. So 
passing random as the second arg is the same as omitting the second arg.

One reason to provide your own random function would be if you have one 
that is more random than the standard function, for example os.urandom() 
or a function based on an external random source such as 
http://www.fourmilab.ch/hotbits/. The random number generator in Python 
(Mersenne twister) is very high quality but that hasn't always been the 
case and it is still deterministic.

You might be interested in the Wikipedia article:
http://en.wikipedia.org/wiki/Random_number_generator
http://en.wikipedia.org/wiki/Mersenne_twister

Trying the two versions once each, getting different results and saying 
you can't see that they are different is...an interesting approach :-) 
But seriously, even with a poor random function you would have to call 
shuffle many times and analyze the entire body of results carefully to 
see any problem.

Kent
> Thanks,
>
> Dick Moores
>   
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   




More information about the Tutor mailing list