13

I am wondering if there is a good way to "shake up" a list of items in Python. For example [1,2,3,4,5] might get shaken up / randomized to [3,1,4,2,5] (any ordering equally likely).

amrcsu
  • 185
  • 1
  • 2
  • 8

3 Answers3

42
from random import shuffle

list1 = [1,2,3,4,5]
shuffle(list1)

print list1
---> [3, 1, 2, 4, 5]
roganjosh
  • 11,753
  • 4
  • 29
  • 43
4

Use random.shuffle:

>>> import random
>>> l = [1,2,3,4]
>>> random.shuffle(l)
>>> l
[3, 2, 4, 1]

random.shuffle(x[, random])

Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random().

Assem
  • 10,850
  • 5
  • 53
  • 90
2

random.shuffle it!

In [8]: import random

In [9]: l = [1,2,3,4,5]

In [10]: random.shuffle(l)

In [11]: l
Out[11]: [5, 2, 3, 1, 4]
bakkal
  • 52,363
  • 10
  • 119
  • 104