random.shuffle question

Christophe Delord christophe.delord at free.fr
Mon Sep 9 19:35:42 CEST 2002


It works but not as you may expect.

l[4:8] is another list made with l[4] to l[7] and changing l[4:8] does not change l. For example :

>>> l = [1,2,3,4,5,6,7,8,9]
>>> l2 = l[4:8]
>>> l2[2] = 99
>>> l2
[5, 6, 99, 8]
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9]

So when you shuffle l[4:8] you shuffle a copy of a sublist of l. In the previous example you can consider that l2 is the argument given to shuffle.

One solution is to shuffle the sublist and copy the sublist in the list:

>>> l = [1,2,3,4,5,6,7,8,9]
>>> l2 = l[4:8]
>>> random.shuffle(l2)
>>> l[4:8] = l2
>>> l
[1, 2, 3, 4, 6, 7, 8, 5, 9]


But this may be inefficient on larger lists.


Christophe.


On Mon, 09 Sep 2002 16:51:11 GMT
"dsavitsk" <dsavitsk at e-coli.net> 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?
> 
> -d
> 
> 


-- 

(o_   Christophe Delord                   _o)
//\   http://christophe.delord.free.fr/   /\\
V_/_  mailto:christophe.delord at free.fr   _\_V



More information about the Python-list mailing list