CS61A(13): Mutable Values

This is the lecture note of CS61A - Lecture 13.

Objects

Object is an important concept in software engineering.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Object Examples

>>> from datetime import date
>>>
>>> date
<class 'datetime.date'>
>>>
>>> today = date(2020, 10, 2)
>>> today
datetime.date(2020, 10, 2)
>>> freedom = date(2020, 12, 17)
>>> str(freedom - today)
'76 days, 0:00:00'
>>>
>>>
>>> today.year # we use dot expression to access objects' attributes or methods
2020
>>> today.month
10
>>> today.strftime('%A %B %d')
'Friday October 02'

String

Strings are objects, so they have attributes and methods. Let's see some examples.

1
2
3
4
5
6
7
8
9
>>> s = 'Hello'
>>> s.upper()
'HELLO'
>>> s.lower()
'hello'
>>> s.swapcase()
'hELLO'
>>> s
'Hello'
1
2
3
4
5
>>> a = 'A'
>>> ord(a)
65
>>> hex(ord(a))
'0x41'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> from unicodedata import name, lookup
>>>
>>> name('A')
'LATIN CAPITAL LETTER A'
>>> name('あ')
'HIRAGANA LETTER A'
>>> name('啊')
'CJK UNIFIED IDEOGRAPH-554A'
>>> lookup('SOCCER BALL')
'⚽'
>>> lookup('BABY')
'👶'
>>> lookup('BABY').encode()
b'\xf0\x9f\x91\xb6'

Mutation Operations

Only objects of mutable types can change their value over time.

  • list
  • dictionary
  • set

Let's see an example of List.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
>>> suits = ['coin', 'string', 'myriad']  # A list literal
>>>
>>>
>>> original_suits = suits # two names with the same object!!!
>>>
>>>
>>> suits.pop() # Removes and returns the final element
'myriad'
>>> suits.remove('string') # Removes the first element that equals the argument
>>> suits
['coin']
>>> suits.append('cup') # Add an element to the end
>>> suits.extend(['sword', 'club']) # Add all elements of a list to the end
>>> suits
['coin', 'cup', 'sword', 'club']
>>> suits[2] = 'spade' # Replace an element
>>> suits
['coin', 'cup', 'spade', 'club']
>>> suits[0:2] = ['heart', 'diamond'] # Replace a slice
>>> suits
['heart', 'diamond', 'spade', 'club']
>>> [suit.upper() for suit in suits]
['HEART', 'DIAMOND', 'SPADE', 'CLUB']
>>> original_suits
['heart', 'diamond', 'spade', 'club'] # All names that refer to the same object are affected by a mutation
>>> [suit[1:4] for suit in suits if len(suit) == 5]
['ear', 'pad']

Let's see another example of Dictionary.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> numerals = {'I': 1.0, 'V': 5, 'X': 10}
>>>
>>> numerals['X']
10
>>> numerals['X'] = 11
>>> numerals['L'] = 50
>>> numerals
{'I': 1.0, 'V': 5, 'X': 11, 'L': 50}
>>>
>>> numerals.pop('X')
11
>>> numerals.get('X')
>>> numerals
{'I': 1.0, 'V': 5, 'L': 50}
>>> sum(numerals.values())
56.0
>>> dict([(3, 9), (4, 16), (5, 25)])
{3: 9, 4: 16, 5: 25}

Tuples

Tuples are immutable sequences, meaning they are unchangable.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
>>> (3, 4, 5, 6)
(3, 4, 5, 6)
>>> 3, 4, 5, 6 # special syntax
(3, 4, 5, 6)
>>> ()
()
>>> tuple()
()
>>> tuple([1, 2, 3])
(1, 2, 3)
>>> tuple(2) # special
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> (2,)
(2,)
>>> 2,
(2,)
>>> (3, 4) + (5, 6)
(3, 4, 5, 6)
>>> 5 in (3, 4, 5)
True
>>>
>>>
>>> {[1]: 2} # mutable value cannot be key
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> {(1, 2): 3} # immutable value can be key
{(1, 2): 3}
>>> {([1], 2): 3} # contain mutable sequence
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

However, an immutable sequence may still change if it contains a mutable value as an element.

1
2
3
4
5
6
7
8
>>> s = ([1, 2], 3)
>>> s[0] = 4
ERROR

>>> s = ([1, 2], 3)
>>> s[0][0] = 4
>>> s
([4, 2], 3)

Mutation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> a = [10]
>>> b = a
>>> a == b
True
>>> a.append(20)
>>> a == b
True
>>> b
[10, 20]


>>> a = [10]
>>> b = [10]
>>> a == b
True
>>> b.append(20)
>>> a == b
False
1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> [10] == [10]
True
>>> [10] is [10]
False

>>> a = [10]
>>> b = a
>>> a is b
True

>>> a = [10]
>>> b = [10]
>>> a is b
False

Example: Lists

You should watch this video to finish some challenge problems.