1

In python if assign a list of numbers to a variable in the following way

>>>a=range(4)
>>>b=a
>>>a[2]=9
>>>b
[0,1,9,3]

but when I assign a single variable in a similar way I get the following result

>>>a=1
>>>b=a
>>>a=2
>>>b
1

Why is it that b=1 instead of b=2 as in the result from assigning the variable to a list?

Anode
  • 371
  • 1
  • 4
  • 9
  • 2
    Because integers are immutable and lists are mutable. – jonrsharpe Jul 11 '14 at 16:51
  • I was going to write something much wordier, but @jonrsharpe explained it much more concisely. – Cory Kramer Jul 11 '14 at 16:52
  • For more detail/examples, check out http://stackoverflow.com/a/8059504/1819790 – pswaminathan Jul 11 '14 at 16:52
  • What other types are mutable/immutable? – Anode Jul 11 '14 at 16:53
  • 1
    @Anode you can read about the built-in types in [the documentation](https://docs.python.org/2/library/stdtypes.html). You might also find [this](http://nedbatchelder.com/text/names.html) useful. – jonrsharpe Jul 11 '14 at 16:54
  • @jonrsharpe Isn't explaining the output solely with mutability a little misleading here? Even if integers were mutable, the second code snippet would lead to two names, `a` and `b`, pointing to different integer objects. – timgeb Jul 11 '14 at 17:03

2 Answers2

3

In your first example, a and b are both references to the same object, a list. When you change the list, so does the output for a and b (which still point to the same list). In your second example, you are assigning a new integer object to the name a. a and b are two different objects with different ids now. Demo:

>>> a = range(4)
>>> b = a
>>> id(a)
38845472
>>> id(b)
38845472
>>> a=1
>>> b=a
>>> id(a)
33619048
>>> id(b)
33619048
>>> b=2
>>> id(a)
33619048
>>> id(b)
33619024
timgeb
  • 76,762
  • 20
  • 123
  • 145
-2

Integers are immutable so to speak, that you can not change them with slicing, unlike lists:

>>> x = range(4)
>>> x
[0, 1, 2, 3]
>>> id(x)
4300734408
>>> x[0] = 5
>>> id(x)
4300734408
>>> x = 1
>>> id(x)
4299162584
>>> x+=1
>>> id(x)
4299162560
>>> 

As you can see above, you can change the list, but it still has the same id. However, if you call += on an integer, the id changes.

This is exactly why although you change a, b doesn't change along with it.

ZenOfPython
  • 891
  • 6
  • 15