0

I'm trying to randomly swap two indexes in a list and then append that list to another list. I wrote the following code:

import random

def swap(arr):
    for i in range(len(arr)):
        y = random.randrange(0,len(arr))
        temp = arr[i]
        arr[i] = arr[y]
        arr[y] = temp
    return arr

Array = [0,1,2,3]
results = []
for i in range(10):
    a = []
    a = swap(Array)
    results.append(a)

print(results)

The array is getting shuffled every time, but when I print out results at the end, every index is the same ordering of the last array appended to it. For example after one run through results was: [[0, 2, 1, 3], [0, 2, 1, 3], [0, 2, 1, 3], [0, 2, 1, 3], [0, 2, 1, 3], [0, 2, 1, 3], [0, 2, 1, 3], [0, 2, 1, 3], [0, 2, 1, 3], [0, 2, 1, 3]]

EliadL
  • 6,230
  • 2
  • 26
  • 43
  • 1
    You're just `swap`ping the same `Array` array over and over. Did you mean to put a copy of `Array` in `a`, then `swap` `a`? – Carcigenicate Feb 26 '19 at 23:23
  • 1
    Change `a` to `a = Array[:]` (as noted in the duplicate), then give `a` to `swap`. – Carcigenicate Feb 26 '19 at 23:28
  • @mkrieger1 That's not relevant. They aren't multiplying lists here. – Carcigenicate Feb 26 '19 at 23:29
  • But they're changing lists in lists, which are reflected accross sublists unexpectedly. – mkrieger1 Feb 26 '19 at 23:32
  • @Carcigenicate I'm trying to swap the same array multiple times and then look at the number of occurrences of each permutation. – Jared Hood Feb 26 '19 at 23:33
  • @JaredHood The `results` list contains many references to the same original list, which, when shuffled, shuffles all of them equally. You need to create a new *copy* of the original list before shuffling it and adding it to the `results`. – mkrieger1 Feb 26 '19 at 23:34
  • @JaredHood Then you're going to need to make a copy of the list after each set of swaps, and use the copy in the next iteration. You're adding the same list to `results` over and over again, and just changing the same list over and over. – Carcigenicate Feb 26 '19 at 23:35
  • Got it. Thanks! – Jared Hood Feb 26 '19 at 23:38

1 Answers1

0

You keep passing the same mutable Array object to the swap function.
Therefore your result ends up listing that same object 10 times.

You can fix this if you change:

a = swap(Array)

to:

a = swap(Array[:])

When you type Array[:] it creates a new list object of all the items.

Credit also due to some of your question's commenters.

EliadL
  • 6,230
  • 2
  • 26
  • 43