This question already has answers here:
Closed 4 years ago.
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).
from random import shuffle
list1 = [1,2,3,4,5]
shuffle(list1)
print list1
---> [3, 1, 2, 4, 5]
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().
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]