The following exercises are based on the concept map previously developed: difference between mutable (lists) and immutable (tuple).
- Suppose we define the following tuple “a” and list “b” as follows:
`»> a=(1,2,3,4)
id_number_a = id(a)
a+=(5,6,7)
id_number_a_extended = id(a)`
` »> b=[1,2,3,4]
id_number_b = id(b)
b+=[5,6,7]
id_number_b_extended = id(b)
`
Which one of the following statements will return True
?
a) >>> a == b
b) >>> id_number_a == id_number_a_extended
c) >>> id_number_b == id_number_b_extended
d) >>> id_number_a == id_number_b
Note that id() returns the “identity” of an object which might change during the lifetime of the variable (see documentation).
2. The following code should sort and compute the power of each of the numbers within the list “l
”. Think about it and complete the “???
” by choosing variable.sort()
or sorted(variable)
. Note that the primer is a mutable action whereas the latter is an immutable one.
`»> l = [3,5,1,2,4]
l_2 = [x*x for x in ???]`
Why one of the actions rise an error?
Source: These exercises are based on Chema Cortés’ blog entries (1, 2)