list.append() doesn't keep shuffled values

Viewed 81

I have the following code:

list =[] 
list1 = ['Dublin', 'Kiev', 'Warsaw', 'Moscow']

for i in range(3):
    random.shuffle(list1)
    list.append(list1) 
list

However, the output keeps the last shuffled value as:

[['Dublin', 'Moscow', 'Kiev', 'Warsaw'],
 ['Dublin', 'Moscow', 'Kiev', 'Warsaw'],
 ['Dublin', 'Moscow', 'Kiev', 'Warsaw']]

I'm really not sure what's happening, and why it behaves this way. Appreciate any replies.

1 Answers

You are appending the reference of the shuffled list, so after 3 iterations you have appended the same reference to the list. since shuffle modifies the list in place and all 3 references point to the same list, then the last shuffle is what all of them will see.

If you want to store the different versions of the shuffle you could append a copy / slice of the list on each shuffle

from random import shuffle

mylist =[]
list1 = ['Dublin', 'Kiev', 'Warsaw', 'Moscow']

for i in range(3):
    shuffle(list1)
    mylist.append(list1[:])
print(mylist)

OUTPUT

[
['Dublin', 'Warsaw', 'Kiev', 'Moscow'], 
['Kiev', 'Dublin', 'Warsaw', 'Moscow'], 
['Kiev', 'Moscow', 'Dublin', 'Warsaw']
]
Related