Randomizing a list in Python

36,895

Solution 1

from random import shuffle

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

print list1
---> [3, 1, 2, 4, 5]

Solution 2

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().

Solution 3

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]
Share:
36,895
amrcsu
Author by

amrcsu

Updated on January 19, 2020

Comments

  • amrcsu
    amrcsu over 4 years

    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).