Given a list x = [1,0,0,1,1]
I can use random.shuffle(x)
repeatedly to shuffle this list, but if I try to do this a for loop the list doesn't shuffle.
For example:
x = [1,0,0,1,1]
k = []
for i in range(10):
random.shuffle(x)
k.append(x)
return x
Basically, k
contains the same sequence of x unshuffled? Any work around?
To use shuffle, import the Python random package by adding the line import random near the top of your program. Then, if you have a list called x, you can call random. shuffle(x) to have the random shuffle function reorder the list in a randomized way.
You can use range() along with list() to generate a list of integers, and then apply random. shuffle() on that list.
Using random. randrange() to select random value from a list. random. randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list, and get the index, and then the corresponding value.
How do you shuffle a list in Python without random? List length n. You could choose an index on [0,n) to swap with the first position. Then choose [1, n) to swap with the second position (index 1).
One pythonic way to create new random-orderings of a list is not to shuffle in place at all. Here is one implementation:
[random.sample(x, len(x)) for _ in range(10)]
Explanation
random.sample
creates a new list, rather than shuffling in place.len(x)
is the size of the sample. In this case, we wish to output lists of the same length as the original list.As mentioned by @jonrsharpe, random.shuffle
acts on the list in place. When you append x
, you are appending the reference to that specific object. As such, at the end of the loop, k
contains ten pointers to the same object!
To correct this, simply create a new copy of the list each iteration, as follows. This is done by calling list()
when appending.
import random
x = [1,0,0,1,1]
k = []
for i in range(10):
random.shuffle(x)
k.append(list(x))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With