Question

I've figured out how to shuffle a list, but the function seems to shuffle everything but the original first item.

My code:

from random import shuffle

x = list(range(10))
print x

k = 0
while k < len(x):
    for i in x:
        shuffle(x)
        print i
        k = k + 1

The reason I'm using a for-loop within a while-loop is that I want the iteration through the list to eventually end, and I'm not sure if this can be done within the for-loop itself.

Running the code will result in print the original list, then 10 print-outs, each an item of the list. The first item printed is always 0, or in other words, it is always the first item in the original list. I can't figure out why this is happening, perhaps because the item has already been "selected" before the shuffle function is called. If that is the case, shuffling the list before the for-loop results in the list being shuffled only once, instead of being shuffled after each item is printed.

Anyone know how I might shuffle that first item before it's printed? Thanks!

Was it helpful?

Solution

Just use

shuffle(x)
for item in x:
    print item

No while loop. No reshuffling. Just like if you were doing it with real flash cards, shuffle once and then present the cards in the order you got by shuffling.

You're seeing the bug you are because on the first iteration of

for i in x:
    shuffle(x)
    print i
    k = k + 1

i is assigned before the shuffle. It doesn't use the shuffled order until the next iteration.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top