1

Possible Duplicate:
Shuffle an array with python

let's say I have a list myList=[1,2,3,4,5],and I want to disorder it randomly:

disorder(myList) # myList is something like [5,3,2,1,4] or [3,5,1,2,4] now

the way I am using is

from random import randint
upperBound = len(myList)-1
for i in range(10):
    myList.insert(randint(0, upperBound), myList.pop(randint(0, upperBound)))

this works, but I think it's obviously inelegant. I am wondering whether there is an elegant and efficient way to achieve my goal.

Community
  • 1
  • 1
Brian
  • 30,156
  • 15
  • 86
  • 87

2 Answers2

13

Use random.shuffle() to shuffle the list in-place:

>>> import random
>>> l = range(10)
>>> l
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.shuffle(l)
>>> l
    [0, 2, 8, 7, 9, 1, 3, 4, 6, 5]
Blender
  • 289,723
  • 53
  • 439
  • 496
9

If you already imported random:

random.shuffle(myList)

It shuffles the myList inplace. It means you have just to run this command, do not use the returning value of this function, which is always None.

eumiro
  • 207,213
  • 34
  • 299
  • 261