Assignment statement binds the variable name and an object.
x =5# Variable 'x' is bound to object 5 of type integerx
5
The same object can have multiple names (⚠️ more on aliasing and copying below)
y = xy
5
# Note that x was overwritten even with addition operation as integers are immutablex +=3x
8
y
5
Strings
String (str) - immutable ordered sequence of characters.
Immutable - individual elements cannot be modified.
Ordered - strings can be sliced (unlike in R).
s ='test's
'test'
s[0] ='r'# immutability
---------------------------------------------------------------------------TypeError Traceback (most recent call last)
Cell In[10], line 1----> 1s[0]='r'# immutabilityTypeError: 'str' object does not support item assignment
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
11760808
id(y)
11760808
x +=3
print(x)print(y)print(id(x))print(id(y))
8
5
11760904
11760808
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);