-3

Coming from R, the following Python code does confuse me:

In [22]: a = [1, 2, 3]
In [23]: b=a
In [24]: b
Out[24]: [1, 2, 3]
In [25]: b[0]=100
In [26]: b
Out[26]: [100, 2, 3]
In [27]: a
Out[27]: [100, 2, 3]

Why does a also change although I only change b?

Timus
  • 10,974
  • 5
  • 14
  • 28
TrungDung
  • 156
  • 3

1 Answers1

3

When you do:

b=a

You are assigning b to the same object as a, i.e. b points to the same object in memory as a

This can be verified with:

>>> b is a
True
sacuL
  • 49,704
  • 8
  • 81
  • 106