Sorted list - how to change it

Tim Chase python.list at tim.thechases.com
Thu Nov 9 06:21:31 EST 2006


>> I have a sorted list for example [1,2,3,4,5] and I would like to change
>> it in a random way
>> e.g [2,5,3,1,4] or [3,4,1,5,2]  or in any other way except being
>> ordered.
>> What is the best/easiest
>>  way how to do it?
>
> use random.shuffel:
> 
>>>> import random
>>>> x = [1,2,3,4,5]
>>>> random.shuffle(x)
>>>> x
> [1, 4, 2, 3, 5]


Just a caveat from past experience...while the OP was talking 
about lists, for future reference random.shuffle() chokes on 
strings (and possibly tuples).  It requires the ability to edit 
the target/parameter in place...a functionality that strings 
don't provide.

Thus, for a "word jumble" program I was playing with, you can't 
just do

	word = 'hello'
	random.shuffle(word)

but rather you have to list'ify the word, shuffle it, then pack 
it back together:

	word = 'hello'
	a = list(word)
	random.shuffle(a)
	word = ''.join(a)

I remember seeing discussion on the list at one point of a 
MutableString class, which might be successfully passed to 
random.shuffle() without hiccuping.

-tkc






More information about the Python-list mailing list