Mutation, Aliasing, Cloning

Aliasing is tricky, and Python tutor is your friend.

Lists in memory:

An analogy

Aliases

a = 1
b = a  #b and a are associated with separate objects
a = 2
print(a)
print(b)

warm = ['red', 'yellow', 'orange']
hot = warm #hot and warm are associated with the same list object
hot.append('pink')
print(hot)
print(warm)
The program prints:
2
1
['red', 'yellow', 'orange', 'pink']
['red', 'yellow', 'orange', 'pink']
Show the global scope and how the variables warm and hot are associated with the same list object, i.e., warm and hot alias, i.e., changing one changes the other!

Cloning a list

This is not the only way to create a new list, there are several other ways, as shown below. In the way above, we simply slice the list with the default begin and end values of 0 and len(cool) respectively. In all the expressions above, the RHS of the assignment simply creates a new list (leaving the original list intact), and then performs the assignment.

Examples:

cool = ['blue', 'green', 'grey']
chill = cool[:]
chill.append('black')
print(chill)
print(cool)
The program prints:
['blue', 'green', 'grey', 'black']
['blue', 'green', 'grey']
Show the global scope and how the variables cool and chill are associated with different list objects.

Sorting Lists

warm = ['red', 'yellow', 'orange']
sortedwarm = warm.sort()
print(warm)
print(sortedwarm)

cool = ['grey', 'green', 'blue']
sortedcool = sorted(cool)
print(cool)
print(sortedcool)
The program prints:
['orange', 'red', 'yellow']
None
['grey', 'green', 'blue']
['blue', 'green', 'grey']
Show the global scope with variables and their associations.

Lists of lists of lists of ...

warm = ['yellow', 'orange']
hot = ['red']
brightcolors = [warm]
brightcolors.append(hot)
print(brightcolors)
hot.append('pink')
print(hot)
print(brightcolors)
The program prints:
[['yellow', 'orange'], ['red']]
['red', 'pink']
[['yellow', 'orange'], ['red', 'pink']]
Show the global scope with variables and their associations. The brightcolors has pointers to the objects that are also pointed-to by warm and hot.

Mutation and Iteration. Try this in Python tutor.