ActiveState Code

Recipe 360461: Fisher Yates Shuffle


Randomly shuffle elements of an array

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import random

def shuffle(ary):
    a=len(ary)
    b=a-1
    for d in range(b,0,-1):
      e=random.randint(0,d)
      if e == d:
            continue
      ary[d],ary[e]=ary[e],ary[d]
    return ary

Comments

  1. 1. At 1:54 p.m. on 22 dec 2004, Dennis Benzinger said:

    How is this different from the shuffle function in the random module?

    http://www.python.org/doc/2.4/lib/module-random.html

Sign in to comment