1

I am trying to find all permutations of elements in a list and add it to a global dictionary

Code:

outp={}
k=0
def func(i,arr):
    global outp
    global k
    arr=arr.copy()
    for j in range(i,len(list)):
        arr[i],arr[j] = arr[j],arr[i]
        if i!=j or i==0:
            k=k+1
            print("\n\n",arr,k)
            outp[k]=arr
            print("\n",outp)
        func(i+1,arr)

list = [1,2,3,8]
func(0,list)

Output below: Till 4th element it updated correctly. During 5th element, it updated both 5th and 3rd element in the dictionary. I don't know why it is happening. Kindly help

[1, 2, 3, 8] 1

 {1: [1, 2, 3, 8]}


 [1, 2, 8, 3] 2

 {1: [1, 2, 3, 8], 2: [1, 2, 8, 3]}


 [1, 3, 2, 8] 3

 {1: [1, 2, 3, 8], 2: [1, 2, 8, 3], 3: [1, 3, 2, 8]}


 [1, 3, 8, 2] 4

 {1: [1, 2, 3, 8], 2: [1, 2, 8, 3], 3: [1, 3, 2, 8], 4: [1, 3, 8, 2]}


 [1, 8, 2, 3] 5

 {1: [1, 2, 3, 8], 2: [1, 2, 8, 3], 3: [1, 8, 2, 3], 4: [1, 3, 8, 2], 5: [1, 8, 2, 3]}
Aditi
  • 820
  • 11
  • 27
  • When you write `outp[k] = arr`, you are basically saying : this value is equal to this object in memory. Meaning that when you modify the object, it is "_updated_" everywhere this data is referenced. – IMCoins Mar 16 '18 at 07:37

2 Answers2

1

You need to place a copy of the array in the dictionary:

outp[k] = arr.copy()
Dan D.
  • 73,243
  • 15
  • 104
  • 123
0

This would be a better way to copy list to a new list.
arr=arr[:] .
https://repl.it/repls/BronzeYellowConversion

  • Why would this be a better way to copy a list than the already given answer? – FlyingTeller Mar 16 '18 at 07:42
  • Slicing is slightly faster. You can search for slicing vs deep copy. or check the comments section of this post https://stackoverflow.com/questions/184643/what-is-the-best-way-to-copy-a-list – Sagar Ruchandani Mar 16 '18 at 07:49
  • That is correct, but `list.copy()` is a shallow copy and equivalent to slicing. Therefore slicing is just a less intuitive way to write a copy – FlyingTeller Mar 16 '18 at 07:53
  • Docs for `list.copy()`: Return a shallow copy of the list. Equivalent to `a[:]`]https://docs.python.org/3/tutorial/datastructures.html) – FlyingTeller Mar 16 '18 at 07:54
  • Fair enough.. by the way, in python2.7, lists don't even have copy method. https://docs.python.org/2.7/tutorial/datastructures.html – Sagar Ruchandani Mar 16 '18 at 07:57