CSC401: Frequently Asked Questions

Aliasing

All variables in python are pointers

When you assign a value to a variable, you point the variable to a new value

Alternatively, you can modify the underlying object pointed to by the variable

y = x sets y to point to the same object as x

If you modify the underlying object pointed to by y, this also modifies the object pointed to by x

... that's because they're both pointing to the same object!

>>> x = ["a"]     
>>> y = x                
>>> y[0] = "b"
>>> print x
['b']                 
>>> print y         
['b']
# Since both x and y point to the same object, modifying the object pointed 
# to by y also modifies the value pointed to by x

If you set y to point to a new object, this does not modify x.

>>> x = ["a"] 
>>> y = x                
>>> y = ["b"]
>>> print x
['a']                 
>>> print y         
['b']
# As you saw above, assigning y to point to a new object does not 
# modify the object pointed to by x

Mutable vs. Immutable

Lists are mutable

Thus, you may modify the underlying object if it is a list

You can also set the variable to point to a new list

Strings are immutable

The underlying object cannot be modified if it is a string

 >>> x = "abcdefg"
>>> y = x
>>> y[0] = "h"
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: object doesn't support item assignment

But you can still set the variable to point to a new string

>>> x = "abcdefg"
>>> y = "h" + y[1:]
>>> print x
abcdefg
>>> print y
hbcdefg

Underlying objects are strictly typed; variables are just pointers

You can always set a variable to point to a value of any type

The same concept applies to elements of lists

>>> x = "abcdefg"
>>> print x
abcdefg
>>> x = ["a"]
>>> print x
["a"]
>>> x[0] = [["b"]]
>>> print x
[[["b"]]]
>>> x[0] = "c"
>>> print x
["c"]

Created by David James for CSC401.