0

I was trying to solve a problem and I encountered this situation:

A = ['2', '3', '4', '1']
B = []
for item in A:
    B += [item]
for i in range(len(A)):
    B[int(A[i]) - 1] = str(i + 1)
    print(int(A[i]) - 1)

The output reads

1
2
3
0

This is fine. However, in my first attempt, I actually did

A = ['2', '3', '4', '1']
B = A
for i in range(len(A)):
    B[int(A[i]) - 1] = str(i + 1)
    print(int(A[i]) - 1)

But this time the output reads

1
0
3
2

I don't see the reason the two outputs being different. I thought in both codes B are similarly defined- which is equal to A at first.

TheLearner
  • 103
  • 4
  • 4
    if you do `B = A`, `A` and `B` both point to the same list object. If you change `A` you change `B` aswell. You can use `B = A.copy()` instead – luigigi Jul 10 '20 at 09:16
  • @luigigi so ```A = B``` means ```B = A```? – TheLearner Jul 10 '20 at 09:22
  • 2
    After the assignment `A = B`, `A is B` and `B is A`. Both variables have a reference to the same value. – Ry- Jul 10 '20 at 09:24
  • This is actually surprising for me. I thought after ```B = A```, the assignment ends, the line runs only once, so changing B will not change A because I do not run ``` B = A ``` again nor ``` A = B ```. Say if I let A = a list, B undefined, and run ```A = B```, I will then get undefined error, although A and B are 'tied together' after ```A = B```. – TheLearner Jul 10 '20 at 09:36
  • And sorry I am rather new here why do I get my text but not codes highlighted in my comment above although I have enclosed the codes with ``` – TheLearner Jul 10 '20 at 09:39

0 Answers0