-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
  • 7,225
  • 5
  • 10
  • 24
TrungDung
  • 136
  • 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
  • 45,929
  • 8
  • 75
  • 99