2

I use a for loop to shuffle a list and append it to another empty list (List A). I can see each shuffled list is different, but the List A has been appended with multiple of the last shuffled list only.

print('---------shuffle list-------------------------------------')
matr=[   ] 

entry=[1, 2, 3, 4, 5, 6, 7, 8, 9]

for i in range(9):
    shuffle(entry )
    print(entry )
    matr.append(entry)

print(matr)

'''
results below:
---------shuffle list-------------------------------------
[3, 1, 7, 5, 8, 9, 2, 6, 4]
[5, 4, 6, 8, 1, 9, 7, 2, 3]
[6, 4, 7, 5, 1, 3, 2, 9, 8]
[4, 9, 8, 1, 7, 3, 6, 5, 2]
[5, 1, 9, 2, 8, 6, 4, 7, 3]
[3, 5, 1, 4, 2, 6, 8, 9, 7]
[1, 2, 4, 6, 7, 8, 3, 9, 5]
[4, 8, 1, 6, 7, 3, 5, 9, 2]
[6, 4, 2, 1, 9, 8, 3, 5, 7]

[[6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7], [6, 4, 2, 1, 9, 8, 3, 5, 7]]

'''

it should have appended each of the shuffled list rather the last shuffled list.

xin pds
  • 73
  • 6
  • Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) and [List of lists changes reflected across sublists unexpectedly Ask Question](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – pault Jun 07 '19 at 02:49

1 Answers1

0

Their same objects, so you gotta do, shuffle is an exception where you need to do this:

matr=[] 

entry=[1, 2, 3, 4, 5, 6, 7, 8, 9]

for i in range(9):
    entry = entry.copy()
    shuffle(entry)
    print(entry)
    matr.append(entry)

print(matr)

Output:

[9, 7, 6, 4, 3, 2, 8, 5, 1]
[4, 3, 2, 8, 7, 1, 5, 9, 6]
[3, 9, 7, 4, 5, 8, 2, 1, 6]
[6, 1, 9, 5, 2, 3, 4, 7, 8]
[5, 4, 7, 9, 8, 2, 6, 3, 1]
[2, 3, 5, 8, 6, 7, 9, 4, 1]
[5, 4, 9, 8, 3, 6, 1, 7, 2]
[5, 1, 2, 3, 7, 8, 6, 9, 4]
[6, 8, 9, 2, 1, 5, 3, 7, 4]
[[9, 7, 6, 4, 3, 2, 8, 5, 1], [4, 3, 2, 8, 7, 1, 5, 9, 6], [3, 9, 7, 4, 5, 8, 2, 1, 6], [6, 1, 9, 5, 2, 3, 4, 7, 8], [5, 4, 7, 9, 8, 2, 6, 3, 1], [2, 3, 5, 8, 6, 7, 9, 4, 1], [5, 4, 9, 8, 3, 6, 1, 7, 2], [5, 1, 2, 3, 7, 8, 6, 9, 4], [6, 8, 9, 2, 1, 5, 3, 7, 4]]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • 1
    Thank you so much U9-Forward. Great. what if another condition is on each row or each column, the number does not duplicate? – xin pds Jun 07 '19 at 05:11