Python list randomization

I am wondering if there is a good way to "shake" a list of elements in Python. For example, it [1,2,3,4,5]can be hacked / randomized to [3,1,4,2,5](any order is equally likely).

+4
source share
3 answers
from random import shuffle

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

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

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 into place. The optional argument random is a 0 argument that returns a random float value in [0.0, 1.0]; from default, this is a random () function.

+4
source

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]
+3

Source: https://habr.com/ru/post/1624845/


All Articles