Understanding variables, references, and assignment
How do variables really work? What happens when we assign a mutable object to two variables? We can easily have two variables that share references to a common object; this can lead to potentially confusing results when the shared object is mutable.
We'll focus on this principle: Python shares references; it doesn't copy data.
To see what this rule on reference sharing means, we'll create two data structures: one is mutable and one is immutable.
Getting ready
We'll create two data structures; one is mutable and one is immutable. We'll use two kinds of sequences, although we could do something similar with two kinds of sets:
>>> mutable = [1, 1, 2, 3, 5, 8]
>>> immutable = (5, 8, 13, 21)
We'll look at what happens when references to these objects are shared.
We can do a similar comparison with a set
and a frozenset
. We can't easily do this...