Coder Perfect

Python can shuffle an array and randomize the order of the items in an array.

Problem

What is the most straightforward way to shuffle an array in Python?

Asked by davethegr8

Solution #1

import random
random.shuffle(array)

Answered by David Z

Solution #2

import random
random.shuffle(array)

Answered by Douglas Leeder

Solution #3

An alternative method is to use sklearn.

from sklearn.utils import shuffle
X=[1,2,3]
y = ['one', 'two', 'three']
X, y = shuffle(X, y, random_state=0)
print(X)
print(y)

Output:

[2, 1, 3]
['two', 'one', 'three']

Advantage: You can shuffle numerous arrays at the same time without breaking the mapping. For repeatable behavior, ‘random state’ can govern the shuffling.

Answered by Qy Zuo

Solution #4

The other answers are the easiest, however it’s a bit annoying that the random.shuffle method doesn’t actually return anything – it just sorts the given list. If you want to chain calls or just be able to declare a shuffled array in one line you can do:

    import random
    def my_shuffle(array):
        random.shuffle(array)
        return array

Then you can say something like:

    for suit in my_shuffle(['hearts', 'spades', 'clubs', 'diamonds']):

Answered by Mark Rhodes

Solution #5

You can use sample: to create a new array if you need one.

import random
new_array = random.sample( array, len(array) )

Answered by Charlie Parker

Post is based on https://stackoverflow.com/questions/473973/shuffle-an-array-with-python-randomize-array-item-order-with-python