Having multiple names for the same object doesn’t usually create a problem with immutable types, as the entire object just gets overwritten.
x =5y = x # Object 5 of type integer is not copied, y is just an alias!
x
5
y
5
id(x) # function id() prints out unique object identifier
11759912
id(y)
11759912
x +=3
print(x)print(y)print(id(x))print(id(y))
8
5
11760008
11759912
Aliasing vs Copying - Mutable
l = [1, 2, 3]
# Object [1, 2, 3] of type list is not copied, l1 is just an alias!l1 = l
# Both [:] slicing notation and copy method create copiesl2 = l[:]l3 = l.copy()
l1.pop(0) # Remove (and return) first element of the listl2.insert(0, 0) # Insert 0 as the first element of the listl3.append(4) # Append 4 to the end of the list
print(l)print(l1)print(l2)print(l3)
[2, 3]
[2, 3]
[0, 1, 2, 3]
[1, 2, 3, 4]
Exercise: Working with Lists
Below is a shuffled version of the first 11 elements of Fibonacci sequence.
Create a copy of the shuffled list;
Remove the last element;
Sort it from smaller integers to larger;
Select the second smallest and the third largest integers in the sequence; Print them out;
Replace them in the list with the string, containing word corresponding to that number (e.g. ‘two’ for 2);