L-3

Python Collections
and Loops

ENGG1330
Computer Programming I

HKU School of Computing and Data Science

L-2: How Confident Do You Feel?

Not yet confident
10%
Can start, but need help
35%
Solve familiar tasks independently
35%
Adapt a solution to a new task
20%

55% feel ready to work independently
45% still need support

L-2: What Felt Most Difficult?

Nothing in particular
54%
Reading expressions
14%
Assignment and +=
10%
Floor division and remainder
9%
Strings and numbers
7%
Variables and updating values
6%
2

L-2: What Did the Quiz Reveal?

97% correct

70% correct

x = 5y = xx += 2print(y)
Download: lec_03_quiz_assignment.py
3

Participation

Lecture L-171.2%
Lecture L-292.1%
Tutorial T-196.2%
4

Tuples

ENGG1330
Computer Programming I

HKU School of Computing and Data Science
5

A Tuple Is an Ordered Sequence

fruits = ('apple', 'orange', 'pear', 'banana')print(fruits)print(fruits[0])
Download: lec_03_example_03.py

fruits

0123
appleorangepearbanana

fruits[0]

0123
appleorangepearbanana
6

Indexing Works Like a String

fruits = ('apple', 'orange', 'pear', 'banana')s = 'apple'print(fruits[0])print(s[0])
Download: lec_03_example_04.py
7

One Tuple Can Mix Types

t = (3, 3.14159, 'Bruce Lee', True)print(type(t))print(type(t[0]))print(type(t[1]))
Download: lec_03_example_06.py
8

A Tuple Can Contain Tuples

t = ((1, 2), (2, 3), (3, 3))print(t)print(len(t))print(t[0])print(len(t[0]))
Download: lec_03_example_07.py
9

Unpacking Assigns Several Names

t = 'Dirk Schnieders', 29, 'A-'name, age, grade = tprint('Name:', name)print('Age:', age)print('Grade:', grade)
Download: lec_03_example_08.py

Unpack t into three names

nameagegrade
Dirk Schnieders29A-

name

nameagegrade
Dirk Schnieders29A-

age

nameagegrade
Dirk Schnieders29A-

grade

nameagegrade
Dirk Schnieders29A-
10

Joining Tuples with +

t1 = (1, 2, 3, 4, 5, 6)t2 = (7, 8, 9)t = t1 + t2print(t)
Download: lec_03_example_09.py
11

A Slice Stops Before the Stop Index

fruits = ('kiwi', 'strawberry', 'apple', 'orange', 'pear', 'banana')print(fruits[1:3])print(fruits[:3])print(fruits[2:])
Download: lec_03_example_10.py

fruits[1:3]

fruits[:3]

fruits[2:]

012345
kiwistrawberryappleorangepearbanana
12

Negative Indices Count from the End

t = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)print(t[-5:])print(t[-3:])print(t[:-3])
Download: lec_03_example_11.py

t[-5:]

t[-3:]

t[:-3]

-10-9-8-7-6-5-4-3-2-1
0123456789
13

A Slice Can Specify a Step

t = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)print(t[0:10])print(t[0:10:2])print(t[0::2])print(t[::2])
Download: lec_03_example_12.py

t[0:10]

t[0:10:2]

t[0::2]

t[::2]

01234567891011121314
01234567891011121314
14

Lists

ENGG1330
Computer Programming I

HKU School of Computing and Data Science
15

Lists Use Square Brackets

fruits = ['apple', 'orange', 'pear', 'banana']print(fruits[-2])print(fruits[-1])print(fruits[-3])print(len(fruits))
Download: lec_03_example_14.py

fruits[-2]

-4-3-2-1
appleorangepearbanana

fruits[-1]

-4-3-2-1
appleorangepearbanana

fruits[-3]

-4-3-2-1
appleorangepearbanana

len(fruits) = 4

-4-3-2-1
appleorangepearbanana
16

Tuple Elements Cannot Be Replaced

fruits = ('apple', 'orange', 'pear', 'banana')fruits[-1] = 'pineapple'print(fruits)
Download: lec_03_example_15.py
17

List Elements Can Be Replaced

fruits = ['apple', 'orange', 'pear', 'banana']fruits[-1] = 'pineapple'print(fruits)
Download: lec_03_example_16.py
18

Two Names Can Refer to the Same List

a = ['apple', 'pear']b = ab[0] = 'kiwi'print('a:', a, 'b:', b)b = ['banana']print('a:', a, 'b:', b)
Download: lec_03_shared_list.py

b = a: both names refer to the same list

ab['apple', 'pear']

b[0] = 'kiwi': the shared list changes

ab['kiwi', 'pear']

b = ['banana']: only b refers to the new list

ab['kiwi', 'pear']['banana']
19

Choosing a Tuple or a List

TupleList (Default)
A fixed group of related valuesA general collection of items
(name, age, grade)['apple', 'orange']
Prevents accidental
element replacement
Add, remove, or replace items

Tuples usually use less memory and can be dictionary keys
when all their elements are hashable

A variable can refer to a different tuple

20

Adding an Item to a List

fruits = []fruits.append('apple')fruits.append('orange')fruits.insert(1, 'pineapple')print(fruits)
Download: lec_03_example_18.py

append('apple')

0
apple

append('orange')

01
appleorange

insert(1, 'pineapple')

012
applepineappleorange
21

Deleting an Item from a List

fruits = ['apple', 'orange', 'pear', 'banana']fruits.insert(2, 'pineapple')print(fruits)del fruits[2]print(fruits)
Download: lec_03_example_19.py

insert(2, 'pineapple')

01234
appleorangepineapplepearbanana

del fruits[2]: later items shift left

0123
appleorangepearbanana
22

Finding Help for a Method

fruits = ['apple', 'orange', 'pear']help(fruits.pop)
Download: lec_03_example_20.py
23

Python Documentation

24

Dictionaries

ENGG1330
Computer Programming I

HKU School of Computing and Data Science
25

A Dictionary Maps Keys to Values

fruit_by_code = {10: 'apple', 20: 'orange',                 30: 'pear', 40: 'banana'}print(fruit_by_code[20])print(fruit_by_code[10])
Download: lec_03_example_22.py

fruit_by_code[20]

10203040
appleorangepearbanana

fruit_by_code[10]

10203040
appleorangepearbanana
26

Keys Can Be Strings or Numbers

fruits = {'favourite': 'apple',          10: 'orange', 20: 'pear', 30: 'banana'}print(fruits['favourite'])print(fruits[10])
Download: lec_03_example_23.py

fruits['favourite']

'favourite'102030
appleorangepearbanana

fruits[10]

'favourite'102030
appleorangepearbanana
27

Looking Up a Mood

mood = {'sunny': ':-)',        'cloudy': ':-|',        'rainy': ':-('}print(mood['sunny'])print(mood['rainy'])
Download: lec_03_example_24.py

mood['sunny']

'sunny''cloudy''rainy'
:-):-|:-(

mood['rainy']

'sunny''cloudy''rainy'
:-):-|:-(
28

Updating a Dictionary Value

stock = {'apple': 5, 'bun': 3}print(stock['apple'])stock['apple'] -= 2print(stock['apple'])
Download: lec_03_example_25.py

stock['apple'] = 5

applebun
53

stock['apple'] -= 2

applebun
33
29

Sets

ENGG1330
Computer Programming I

HKU School of Computing and Data Science
30

A Set Stores Distinct Elements

shapes = {'square', 'triangle', 'circle'}print('polygon' in shapes)print('polygon' not in shapes)
Download: lec_03_example_27.py
31

Duplicates Disappear in a Set

shapes = set()  # Create an empty setshapes.add('triangle')shapes.add('circle')shapes.add('triangle')print(shapes)shapes.add('polygon')print(shapes)
Download: lec_03_example_28.py

add('triangle')

shapes'triangle'

add('circle')

shapes'triangle''circle'

add('triangle') again: no duplicate

shapes'triangle''circle'

add('polygon')

shapes'triangle''circle''polygon'
32

Removing an Element from a Set

shapes = {'square', 'triangle', 'circle', 'polygon'}shapes.remove('square')print(shapes)
Download: lec_03_example_29.py
33

Useful Set Operations

OperationPythonMeaning
Subsets <= tEvery element of s is in t
Supersets >= tEvery element of t is in s
Unions | tElements from either set
Intersections & tElements common to both
Differences - tElements in s, but not t
Symmetric differences ^ tElements in exactly one set
34

Intersection Finds Shared Elements

s1 = {0, 2, 4, 6, 8, 10, 12}s2 = {0, 3, 6, 9, 12}print(s1 & s2)
Download: lec_03_example_31.py

Compare membership in the two sets

s1s22, 48, 10390612

s1 & s2: present in both

s1s22, 48, 10390612
35

While Loops

ENGG1330
Computer Programming I

HKU School of Computing and Data Science
36

A Loop Repeats Its Body

Body
The statements that repeat

Iteration
One repetition of the body

37

while Checks Before Each Iteration

count = 0while count < 3:    print(count)    count += 1print('Done')
Download: lec_03_example_35.py
Condition
Loop body
After the loop
38

Updating the Counter Ends This Loop

count = 0while count < 3:    print('8')    count += 1
Download: lec_03_example_36.py
Update
39

Repeat Until the Answer Is Correct

answer = 0while answer != 4:    answer = int(input('2 * 2 = '))print('Well done. Here is a cookie!')
Download: lec_03_example_37.py
40

Counting the Attempts

answer = 0count = 0while answer != 4:    answer = int(input('2 * 2 = '))    count += 1print('Well done. Here is a cookie!')print('It took you', count, 'attempts.')
Download: lec_03_example_38.py
41

A Loop Can Contain Another Loop

i = 0while i < 2:    j = 0    while j < 2:        print(i, j)        j += 1    i += 1
Download: lec_03_example_39.py

The inner loop runs for each i

ijPrinted pair
000 0

Advance j

ijPrinted pair
010 1

Advance i, then reset j to 0

ijPrinted pair
101 0

Advance j again

ijPrinted pair
111 1
42

For Loops

ENGG1330
Computer Programming I

HKU School of Computing and Data Science
43

for Visits Each Element

primes = [2, 3, 5, 7]for prime in primes:    print(prime)print('Done')
Download: lec_03_example_41.py
Next element
Loop body
After the loop
44

A Loop Can Build a Running Total

scores = (4, 7, 3)total = 0for score in scores:    total += score    print(total)print('Final:', total)
Download: lec_03_example_42.py

Start total at 0

scoretotal
Not read yet0

0 + 4 = 4

scoretotal
44

4 + 7 = 11

scoretotal
711

11 + 3 = 14

scoretotal
314

The loop has finished

Final total
14
45

Keeping the Largest Value Seen

scores = (4, 7, 3, 9, 6)best = scores[0]for score in scores:    if score > best:        best = score    print(score, best)
Download: lec_03_running_maximum.py

Start with the first score

scorebest
Not read yet4

4 > 4 is false: keep best

scorebest
44

7 > 4 is true: update best

scorebest
77

3 > 7 is false: keep best

scorebest
37

9 > 7 is true: update best

scorebest
99

6 > 9 is false: keep best

scorebest
69
46

Looping Through a String

for c in 'Dirk':    print(c)
Download: lec_03_example_43.py
47

Looping Through Dictionary Keys

mood = {'sunny': ':-)', 'cloudy': ':-|', 'rainy': ':-('}for key in mood:    print('Key:', key, 'Value:', mood[key])
Download: lec_03_example_44.py
48

range Stops Before Its Stop Value

for x in range(3, 8):    print('->', x)
Download: lec_03_example_45.py

range(3, 8): start included, stop excluded

345678
34567Excluded

The first iteration

345678
34567Excluded

The last iteration

345678
34567Excluded
49

Nested for Loops

for i in range(2):    for j in range(2):        print(i, j)
Download: lec_03_example_46.py

First outer value, first inner value

ijPrinted pair
000 0

Advance the inner loop

ijPrinted pair
010 1

The next outer value starts a new inner loop

ijPrinted pair
101 0

Advance the inner loop again

ijPrinted pair
111 1
50

A Decision Inside a Loop

for i in range(1, 5):    if i % 2 == 0:        print(i)    else:        print('odd')
Download: lec_03_example_47.py
51

A Negative Step Counts Down

num = int(input('Number: '))for i in range(num, 0, -1):    print(i)print('Blast off!')
Download: lec_03_example_48.py
52

Using an Index in a Loop

fruits = ('apple', 'orange', 'pear', 'banana')for i in range(len(fruits)):    print(i, '=', fruits[i])
Download: lec_03_example_49.py

i = 0: fruits[i] = 'apple'

0123
appleorangepearbanana

i = 1: fruits[i] = 'orange'

0123
appleorangepearbanana

i = 2: fruits[i] = 'pear'

0123
appleorangepearbanana

i = 3: fruits[i] = 'banana'

0123
appleorangepearbanana
53

enumerate Gives the Index and Value

fruits = ('apple', 'orange', 'pear', 'banana')for index, value in enumerate(fruits):    print(index, '=', value)
Download: lec_03_example_50.py

index = 0, value = 'apple'

0123
appleorangepearbanana

index = 1, value = 'orange'

0123
appleorangepearbanana

index = 2, value = 'pear'

0123
appleorangepearbanana

index = 3, value = 'banana'

0123
appleorangepearbanana
54

break Leaves the Loop

for val in 'string':    if val == 'i':        break    print(val)print('Done')
Download: lec_03_example_51.py
Leave the loop
55

continue Skips to the Next Iteration

for val in 'string':    if val == 'i':        continue    print(val)print('Done')
Download: lec_03_example_52.py
Next iteration
56

Complete the full survey during the lecture

57

To Earn Your Participation Mark

  • Complete the full survey during the lecture
  • Pass all tests in at least 3 of the 5 challenges
    by 23:59 HKT today

Both required · 1 mark · No partial credit

58