Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop though range and randomly shuffle a list in Python?

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, kcontains the same sequence of x unshuffled? Any work around?

like image 583
Teodorico Levoff Avatar asked Feb 28 '18 22:02

Teodorico Levoff


People also ask

How do you randomly scramble a list in Python?

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.

How do you shuffle a range in Python?

You can use range() along with list() to generate a list of integers, and then apply random. shuffle() on that list.

Is there a way to randomize a list in Python?

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?

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).


2 Answers

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.
  • List comprehensions are often considered pythonic versus explicit for loops.
like image 92
jpp Avatar answered Sep 18 '22 16:09

jpp


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))
like image 43
Windmill Avatar answered Sep 16 '22 16:09

Windmill