random.shuffle question
Erik Max Francis
max at alcyone.com
Mon Sep 9 14:23:15 EDT 2002
dsavitsk wrote:
> why does this not work to shuffle part of a list?
>
> >>> l = [1,2,3,4,5,6,7,8,9]
> >>> random.shuffle(l[4:8])
> >>> print l
> [1, 2, 3, 4, 5, 6, 7, 8, 9]
>
> and more importantly, is there a better way to do this?
random.shuffle shuffles the list you hand it, and when you create a
slice of a list, that sublist is separate from the original list. So
you're creating a new sublist, shuffling it, and then tossing it away.
You could simply chop up the list, shuffle the part that you want, and
then reassemble it:
>>> import random
>>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lBegin = l[:4]
>>> lMiddle = l[4:8]
>>> lEnd = l[8:]
>>> random.shuffle(lMiddle)
>>> l2 = lBegin + lMiddle + lEnd
>>> l2
[1, 2, 3, 4, 6, 5, 8, 7, 9]
--
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ The perfection of innocence, indeed, is madness.
\__/ Arthur Miller
Max Pandaemonium / http://www.maxpandaemonium.com/
A sampling of Max Pandameonium's music.
More information about the Python-list
mailing list