0

I have written the following while loop:

nums = [1,2,3]

permutation_set = []
pointer_stand = 0
pointer_runner = 0
original_nums = nums[:]
permutation_set.append(original_nums)



while pointer_runner < len(nums)-1:

    pointer_runner +=1
    nums[pointer_stand], nums[pointer_runner] = nums[pointer_runner], nums[pointer_stand]
    permutation_set.append(nums)
    nums = original_nums

print(permutation_set)

The output to me makes no sense at all- I get [[3,2,1],[2,1,3],[3,2,1]]. But shouldn't the first list be simply [1,2,3]? If I remove the while loop completely, then my output is [1,2,3], so my question is, why is the while loop changing the first list? Especially since I DO NOT make any changes to 'original_nums'

heio fhow
  • 19
  • 3
  • Check out [this](https://stackoverflow.com/a/25670170/4680533) answer, The `original_nums` and `nums` both point to the same object – Ed Smith May 16 '21 at 09:16
  • "I DO NOT make any changes to 'original_nums'"—Yeah you do. You set `nums = original_nums` inside your loop, so they refer to the same list; and then you alter the contents of `nums`. – khelwood May 16 '21 at 09:17

2 Answers2

0

You only make a copy the first time you assign original_nums - when you re-assign nums inside your loop, you don't make a copy - you use the original list.

while pointer_runner < len(nums)-1:
    ...
    permutation_set.append(nums)
    nums = original_nums

If you want to create a copy, you'll have to either use the copy module or the slice operator as you already did:

while pointer_runner < len(nums)-1:
    ...
    permutation_set.append(nums)
    nums = original_nums[:]
MatsLindh
  • 49,529
  • 4
  • 53
  • 84
  • Hi Mats, thanks for your answer it makes sense. Similar to my comment above to Khelwood- thought by doing nums = original_nums, doen't 'nums' take the value/reference of original_nums? And if I change 'nums' thereafter it won't change original_nums? Or am I mistaken? – heio fhow May 16 '21 at 09:48
  • Ignore my comment, I see it now! Thanks – heio fhow May 16 '21 at 09:50
0

The problem occurs when you assign nums to original_nums. Don't forget that they are lists. The assignment nums = original_nums just copies the reference to the list, so nums and original_nums refer to the same list. So, when "num" changes, you change automatically original_nums. Since original_nums refers to the first element of permutation_set, consequently you change the first element of permutation_set. Use the builtin copy method nums = original_nums.copy() or slice it nums = original_nums[:] in your while loop