Lists in memory:
An analogy
VIRAT: cricketer, fit, famous
Cheeku: cricketer, fit, famous King Kohli: cricketer, fit, famous
Virat, Cheeku, and King Kohli are aliases for the same person.
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
chill = cool[:]
begin and end values of 0 and len(cool) respectively.
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
sort() mutates the list, returns nothing.sorted() does not mutate the list, must assign result to a variable.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.
def remove_dups(L1, L2):
for e in L1:
if e in L2:
L1.remove(e)
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
remove_dups(L1, L2)
L1 is [2,3,4], not [3,4]. Why?
2.
def remove_dups(L1, L2):
L1_copy = L1[:]
for e in L1_copy:
if e in L2:
L1.remove(e)
Notice that L1_copy = L1 does not clone, need L1_copy = L1[:].