Teodorico Levoff
Teodorico Levoff

Reputation: 1659

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?

Upvotes: 5

Views: 6443

Answers (3)

jpp
jpp

Reputation: 164673

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.

Upvotes: 4

DMe
DMe

Reputation: 7826

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

Upvotes: 2

Miguel
Miguel

Reputation: 1363

Try this:

x = [1,0,0,1,1]
k = []
for i in range(10):
     random.shuffle(x)
     k.append(x.copy())
return x

By replacing x with x.copy() you append to k a new list that looks like x at that moment instead of x itself.

Upvotes: 0

Related Questions