Shuffle an array with python, randomize array item order with python

271,508

Solution 1

import random
random.shuffle(array)

Solution 2

import random
random.shuffle(array)

Solution 3

Alternative way to do this using 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 random multiple arrays simultaneously without disrupting the mapping. And 'random_state' can control the shuffling for reproducible behavior.

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 do lines like:

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

Solution 5

Just in case you want a new array you can use sample:

import random
new_array = random.sample( array, len(array) )
Share:
271,508
davethegr8
Author by

davethegr8

Updated on July 08, 2022

Comments

  • davethegr8
    davethegr8 almost 2 years

    What's the easiest way to shuffle an array with python?

  • John Y
    John Y over 12 years
    It doesn't return anything specifically because it is trying to remind you that it works by altering the input in place. (This can save memory.) Your function alters its input in place also.
  • Mark Rhodes
    Mark Rhodes over 12 years
    I guess it's a style thing. Personally I prefer the fact that I can write a single line to achieve what would take a couple otherwise. It seems odd to me that a language which aims to allow programs to be as short as possible doesn't tend to return the passed object in these cases. Since it alters the input in place, you can replace a call to random.shuffle for a call to this version without issue.
  • John Y
    John Y over 12 years
    Python doesn't actually aim to be as brief as possible. Python aims to balance readability with expressivity. It so happens to be fairly brief, mainly because it is a very high-level language. Python's own built-ins typically (not always) strive to either be "functionlike" (return a value, but don't have side effects) or be "procedurelike" (operate via side effects, and don't return anything). This goes hand-in-hand with Python's quite strict distinction between statements and expressions.
  • Jabba
    Jabba about 12 years
    Nice. I suggest renaming it to my_shuffle to see the difference in the code immediately.
  • Aaron Newton
    Aaron Newton about 12 years
    Maybe, but this could be premature optimization (it could be helpful, but the need to shuffle doesn't explicitly require the need to return the array). Also, shuffle(array) followed by some use of shuffle would only be 2 lines as opposed to 3 + n (times usage), although I guess it would be a saving if you use it many times. Here is a great video that discusses this type of thing (e.g. phantom requirements and premature optimisation) - pyvideo.org/video/880/stop-writing-classes
  • abcd
    abcd almost 8 years
    what does destroyed mean, exactly? (i mean, in this context -- i'm not an ELL.)
  • user781903
    user781903 over 7 years
    yes it returns None, but array is modifed, if you really want to return something then do this import random def shuffle(arr): random.shuffle(arr) return arr
  • Charlie Parker
    Charlie Parker about 7 years
    is there an option that doesn't mutate the original array but return a new shuffled array?
  • Charlie Parker
    Charlie Parker about 7 years
    is there an option that doesn't mutate the original array but return a new shuffled array?
  • David Z
    David Z about 7 years
    @Charlie That would be a good thing to ask in a separate question. (Maybe someone else has already asked it.)
  • Nicholas McCarthy
    Nicholas McCarthy almost 7 years
    Well if I try A = np.array(range(9)).reshape([3,3])
  • Dmitry
    Dmitry over 6 years
    Thanks, it's very useful to shuffle two arrays at once.
  • nOp
    nOp about 6 years
    Was looking for this, TNX!
  • Joshua Huber
    Joshua Huber about 6 years
    Ironically enough, this page is the top hit in Google when I just searched for "python shuffle array"
  • Matt
    Matt almost 6 years
    @Charlie people Google these questions so they can find answers to them on places like stack overflow. As long as it's not a duplicate there's nothing wrong with making stack overflow an option as a resource
  • WestCoastProjects
    WestCoastProjects over 5 years
    this is more complete (and often more useful) than the accepted answer
  • WestCoastProjects
    WestCoastProjects over 5 years
    does this create a new random element for each element of the array?
  • James
    James over 5 years
    @javadba No, this just sort an array by random index which will end up shuffle the array
  • WestCoastProjects
    WestCoastProjects over 5 years
    Sorry i was maybe not clear I did not mean the array I meant the Random element: ie in the lambda the random.random() might be generating new Random class instance each time. I'm not actually sure: in java this would be the wrong way to do it: you should create a Random rng = Random() and then invoke the rng.nextGaussian(). But not sure how python random.random() works
  • LuFFy
    LuFFy over 5 years
    While your code may correct as answer But Elaborating what your code does, It can improve the quality of your answer. Checkout the Article : How do I write a good answer?
  • Bobby Zandavi
    Bobby Zandavi almost 4 years
    @{Charlie Parker} Just make a copy of the original array before using random.shuffle: ` copy_of array = array.copy() random.shuffle(copy_of_array) `
  • James Parker
    James Parker over 3 years
    @CharlieParker new_array = list(array); random.shuffle(new_array)
  • Charlie Parker
    Charlie Parker over 3 years
    for those that don't conceptually see what new_array = list(array); random.shuffle(new_array) does since they are not commands on separate lines. James is first creating a copy and then shuffling the array.
  • allenh
    allenh almost 3 years
    @CharlieParker From the python docs shuffled = sample(array, k=len(array))
  • Amin Pial
    Amin Pial almost 3 years
    for example, you are building an exe or packing your code. Then just to shuffle an array you have to package the whole sklearn in your package!!!. which is not sane. Something works don't mean it is the correct solution. The answer is more of a hack rather than a solution.
  • Tushar Kshirsagar
    Tushar Kshirsagar over 2 years
    out put is none for a4 = np.array((blockshaped(c, 2, 3)))[3] where blockshaped return nd'array
  • David Z
    David Z over 2 years
    @Tushar Despite the name, the object you get from np.array() is not an "array" in the sense of this question. You may want to look for another question to find out how to shuffle a Numpy array specifically. (Or you can search the web to find the right page in the Numpy documentation.)