faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 1 people (100%) answered Yes

Entry

Unsorting (randomizing) a sequence

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 242, Stephan Houben


"""
Packages: basic_datatypes.lists;maths.random
"""
"""
> Is there a command to do this? (Can't find one but...)
> I've been writing an algorithm myself, but it's incredibly slow and I
> would like something quicker (of course :) )
This works for me:
"""
import random
def randomize(l):
    length = len(l)
    for i in range(length):
        j = rand.randrange(i, length)
        l[i], l[j] = l[j], l[i]
"""
Note that this randomizes the list in-place.
Greetings,
Stephan
"""