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) )
Author by
davethegr8
Updated on July 08, 2022Comments
-
davethegr8 almost 2 years
What's the easiest way to shuffle an array with python?
-
John Y over 12 yearsIt 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 over 12 yearsI 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 over 12 yearsPython 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 about 12 yearsNice. I suggest renaming it to my_shuffle to see the difference in the code immediately.
-
Aaron Newton about 12 yearsMaybe, 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 almost 8 yearswhat does destroyed mean, exactly? (i mean, in this context -- i'm not an ELL.)
-
user781903 over 7 yearsyes 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 about 7 yearsis there an option that doesn't mutate the original array but return a new shuffled array?
-
Charlie Parker about 7 yearsis there an option that doesn't mutate the original array but return a new shuffled array?
-
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 almost 7 yearsWell if I try A = np.array(range(9)).reshape([3,3])
-
Dmitry over 6 yearsThanks, it's very useful to shuffle two arrays at once.
-
nOp about 6 yearsWas looking for this, TNX!
-
Joshua Huber about 6 yearsIronically enough, this page is the top hit in Google when I just searched for "python shuffle array"
-
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 over 5 yearsthis is more complete (and often more useful) than the accepted answer
-
WestCoastProjects over 5 yearsdoes this create a new random element for each element of the array?
-
James over 5 years@javadba No, this just sort an array by random index which will end up shuffle the array
-
WestCoastProjects over 5 yearsSorry i was maybe not clear I did not mean the
array
I meant theRandom
element: ie in thelambda
therandom.random()
might be generating newRandom
class instance each time. I'm not actually sure: injava
this would be the wrong way to do it: you should create aRandom rng = Random()
and then invoke therng.nextGaussian()
. But not sure how pythonrandom.random()
works -
LuFFy over 5 yearsWhile 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 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 over 3 years@CharlieParker
new_array = list(array); random.shuffle(new_array)
-
Charlie Parker over 3 yearsfor 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 almost 3 years@CharlieParker From the python docs
shuffled = sample(array, k=len(array))
-
Amin Pial almost 3 yearsfor 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 over 2 yearsout put is none for a4 = np.array((blockshaped(c, 2, 3)))[3] where blockshaped return nd'array
-
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.)