5

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?

4
  • 5
    random.shuffle is in place. You're filling k with references to the same list, so all ten lists in the result will be in the same random order. Maybe try a shallow copy, k.append(x[:])? Commented Feb 28, 2018 at 22:53
  • @jonrsharpe But In the python shell, I am able to continually execute random.shuffle(x) and checking x after each call, x does get shuffled. Commented Feb 28, 2018 at 22:54
  • Yes, of course it does, I'm not saying otherwise. k actually contains the same sequence of x shuffled, but there are only so many unique orders so sometimes it will be the same as your starting position. Commented Feb 28, 2018 at 22:55
  • @jonrsharpe I see! Now I'm understanding. Commented Feb 28, 2018 at 23:01

3 Answers 3

4

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.
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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.

1 Comment

It would be helpful to explain what you've changed and why.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.