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 4 months

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

  • John Y
    John Y almost 11 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 almost 11 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 almost 11 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 over 10 years
    Nice. I suggest renaming it to my_shuffle to see the difference in the code immediately.
  • Aaron Newton
    Aaron Newton over 10 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 over 6 years
    what does destroyed mean, exactly? (i mean, in this context -- i'm not an ELL.)
  • user781903 almost 6 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 over 5 years
    is there an option that doesn't mutate the original array but return a new shuffled array?
  • Charlie Parker
    Charlie Parker over 5 years
    is there an option that doesn't mutate the original array but return a new shuffled array?
  • David Z
    David Z over 5 years
    @Charlie That would be a good thing to ask in a separate question. (Maybe someone else has already asked it.)
  • Nicholas McCarthy over 5 years
    Well if I try A = np.array(range(9)).reshape([3,3])
  • Dmitry
    Dmitry almost 5 years
    Thanks, it's very useful to shuffle two arrays at once.
  • nOp over 4 years
    Was looking for this, TNX!
  • Joshua Huber
    Joshua Huber over 4 years
    Ironically enough, this page is the top hit in Google when I just searched for "python shuffle array"
  • Matt
    Matt over 4 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 about 4 years
    this is more complete (and often more useful) than the accepted answer
  • WestCoastProjects
    WestCoastProjects about 4 years
    does this create a new random element for each element of the array?
  • James
    James about 4 years
    @javadba No, this just sort an array by random index which will end up shuffle the array
  • WestCoastProjects
    WestCoastProjects about 4 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 about 4 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 over 2 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 about 2 years
    @CharlieParker new_array = list(array); random.shuffle(new_array)
  • Charlie Parker
    Charlie Parker about 2 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 over 1 year
    @CharlieParker From the python docs shuffled = sample(array, k=len(array))
  • Amin Pial over 1 year
    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 about 1 year
    out put is none for a4 = np.array((blockshaped(c, 2, 3)))[3] where blockshaped return nd'array
  • David Z
    David Z about 1 year
    @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.)