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. The rules are simple and the consequences are generally obvious.
We'll focus on this rule: Python shares references. It doesn't copy data.
We need to look at what this rule on reference sharing means.
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: 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)
The mutable data structure can be changed and shared. The immutable data...