Python Programming · Week 7

Lists and Tuples
In class

Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering

Today

Three things

  1. 1 Recap and quiz: the week 7 videos
  2. 2 Exercise 6: all three problems, solved live
  3. 3 Next week: the midterm
Recap · 1

A list

>>>scores = [85, 72, 93, 60]

>>>len(scores)

4

>>>names = ["Kim", "Lee"]

>>>len([])

0

items, in order →

[ 85,72,93,60 ]
len: 4 items
[ ] square brackets , commas between the values
["Kim","Lee"]

strings, too

[]

empty: 0 items

a list: values in order, in one variable · len counts them

Recap · 2

Positions from 0

index 0123 85729360 from the end -4-3-2-1

>>>scores = [85, 72, 93, 60]

>>>scores[0]

85

>>>scores[3]

60

>>>scores[-1]

60

>>>scores[-2]

93

>>>scores[4]

IndexError: list index out of range

an index starts at 0 -1 is the last item
Recap · 3

Slicing

scores[start:stop]

index 0123 85729360
start
stopnot included
stopnot included
[:2] [2:]

[:2] is [0:2]: from the beginning

[2:]: from index 2 to the end

>>>scores = [85, 72, 93, 60]

>>>scores[1:3]

[72, 93]

>>>scores[:2]

[85, 72]

>>>scores[2:]

[93, 60]

start included stop not included

like range(1, 3) → 1, 2

Recap · 4

Slicing with a step

scores[start:stop:step]

index 0123 85729360
stopnot included
⟵ read backwards

like range(0, 3, 2) → 0, 2

[::2]: from the beginning to the end

>>>scores = [85, 72, 93, 60]

>>>scores[0:3:2]

[85, 93]

>>>scores[::2]

[85, 93]

>>>scores[::-1]

[60, 93, 72, 85]

the step: how far to move each time · [::-1]: reversed

Recap · 5

Changing a list

>>>scores = [85, 72, 93, 60]

85729360

>>>scores[1] = 75

85759360

change an item

>>>scores.append(88)

8575936088

add at the endmethod

>>>scores.insert(0, 90)

908575936088

add at a position

>>>scores.pop()

9085759360

take out the last · returns 88

>>>scores.remove(93)

90857560

remove a value

a list can change · list methods change the list itself

Recap · 6

A string cannot change

>>>word = "Python"

>>>word[0] = "J"

TypeError: 'str' object does not support item assignment

>>>word.upper()

'PYTHON'

>>>word

'Python'unchanged

>>>word = word.upper()

>>>word

'PYTHON'

to keep the new string: store it

a new string

>>>" hi ".strip()

'hi'

>>>"Hello".lower()

'hello'

>>>"hello".upper()

'HELLO'

>>>"010-1234-5678".replace("-", " ")

'010 1234 5678'

>>>", ".join(["Kim", "Lee", "Park"])

'Kim, Lee, Park'

a list

>>>"85 72 93".split()

['85', '72', '93']

>>>"Kim,Lee,Park".split(",")

['Kim', 'Lee', 'Park']

True or False

>>>"2026".isdigit()

True

>>>"20a6".isdigit()

False

>>>"Python".startswith("Py")

True

>>>"photo.png".endswith(".png")

True

immutable a string cannot change · string methods return a new value

Recap · 7

sorted() or .sort()?

scores = [85, 72, 93, 60]

new = sorted(scores)

print(new)

print(scores)

[60, 72, 85, 93]

[85, 72, 93, 60]

a new list · scores unchanged

scores = [85, 72, 93, 60]

scores.sort()

print(scores)

[60, 72, 85, 93]

scores itself is sorted

print(scores.sort()) → None .sort() returns None

sorted(): a new list · .sort(): changes the list, returns None

Recap · 8

Two variables, one list

a number · as in week 3

a = 10

b = a

b = b + 1

print(b)

print(a)

11

10

a 10 b 11 a new value for b

a list

a = [10, 20, 30]

b = a

b[0] = b[0] + 1

print(b[0])

print(a[0])

11

?11

a 102030 b one list 11 the list itself changes b: an alias

b = b + 1: a new value for the variable · b[0] = b[0] + 1: a change to the one list

Recap · 9

A function can change a list

a number · week 6

def add_bonus(score):

score = score + 5

score = 80

add_bonus(score)

print(score)

80
score 80 inside add_bonus score 85 a new value, inside only

a list

def add_bonus(scores):

scores[0] = scores[0] + 5

scores = [80, 70]

add_bonus(scores)

print(scores[0])

?85

scores 8070 inside add_bonus scores 85 the list itself changes the call ended: the parameter is gone the change stays

a new value for a parameter stays inside · a change to a list shows outside

Recap · 10

Unpacking

point = (3, 4)

x, y = point

print(x)

print(y)

3

4

point 3 4 two values x y two variables 3 x 4 y

unpacking one variable for each value · in order

Recap · 11

Swapping two variables

a = 1

b = 2

a, b = b, a

print(a)

print(b)

2

1

a, b = b, a the right side first

↓

a, b = 2, 1 b is 2, a is 1

↓

a, b = (2, 1) commas make a tuple

↓

a = 2b = 1 one value each, in order

the right side first, as one tuple · then one value for each variable

Recap · 12

enumerate: position and item

scores = [85, 72, 93, 60]

enumerate(scores) → (0, 85)(1, 72)(2, 93)(3, 60) from 0
enumerate(scores, start=1) → (1, 85)(2, 72)(3, 93)(4, 60) from 1

for i, score in enumerate(scores, start=1):i, score = (1, 85)i, score = (2, 72)i, score = (3, 93)i, score = (4, 60)

print(f"{i}: {score}")

1: 85

2: 72

3: 93

4: 60

enumerate: (position, item) tuples · unpacked in the for line

Quiz

What comes out?

No computer. Say what comes out, then I run it.

1

>>>nums = [10, 20, 30, 40, 50]

>>>nums[1:-1]

>>>nums[::-2]

2

>>>"Le" in ["Kim", "Lee"]

3

>>>a = [1, 2]

>>>b = a

>>>c = a.copy()

>>>a.append(3)

>>>b

>>>c

4

quiz4.py

def reset(items):

items = []

data = [1, 2]

reset(data)

print(data)

5

quiz5.py

def swap(x, y):

x, y = y, x

p = 1

q = 2

swap(p, q)

print(p)

6

quiz6.py

for i, ch in enumerate("hi"):

print(f"{i}: {ch}")

Exercise 6 · Problem 1

Palindrome

week07_problem1.py 2 points

A palindrome reads the same forwards and backwards, such as level. Ask for a word in lowercase letters. If it is a palindrome, print Palindrome. If not, print Not a palindrome.

on the screen · one run

Word: level

Palindrome.

the value after the prompt is typed · the prompt word is up to you

examples · typed values in order

typed

prints

level

Palindrome.

python

Not a palindrome.

racecar

Palindrome.

noun

Not a palindrome.

a

Palindrome.

Exercise 6 · Problem 2

Binary to decimal

week07_problem2.py 3 points

Ask for a binary number (only 0s and 1s), and print its value as a decimal number. For example, 1011 is 8 + 0 + 2 + 1 = 11.

on the screen · one run

Binary: 1011

Decimal: 11

the value after the prompt is typed · the prompt word is up to you

Hint: go through the digits from the right (a slice can reverse a string); their place values are 1, 2, 4, 8, …

examples · typed values in order

typed

prints

1011

Decimal: 11

11111111

Decimal: 255

100000

Decimal: 32

0

Decimal: 0

1

Decimal: 1

Exercise 6 · Problem 3

Readings off the average

week07_problem3.py 5 points

A sensor is read several times. Ask how many readings there are, then each reading. Print the average, then each reading that is more than 10% off, with its position: more than 10% off means its difference from the average is more than 10% of the average.

on the screen · one run

How many readings? 4

Reading 1: 5.1

Reading 2: 6.0

Reading 3: 4.9

Reading 4: 4.0

Average: 5.0

Reading 2: 6.0 is more than 10% off.

Reading 4: 4.0 is more than 10% off.

the values after the prompts are typed · the prompt words are up to you

steps, in words

  1. 1 Read the readings into a list.
  2. 2 Work out the average.
  3. 3 Go through the list again, and print each reading that is more than 10% off, with its position.

examples · typed values in order

typed

prints

4, 5.1, 6.0, 4.9, 4.0

Average: 5.0, then readings 2 and 4

3, 4.8, 5.0, 5.2

Average: 5.0 only

1, 7.5

Average: 7.5 only

5, 12.0, 9.8, 10.2, 10.1, 7.9

Average: 10.0, then readings 1 and 5

Next week

Week 8: Midterm

Midterm: Monday, October 26, 8:00–8:50 a.m., Changhak Hall 123.
Exercise 6: due tomorrow, Tuesday, October 20, 11:59 a.m.
Week 9 videos and exercise 7: up Tuesday–Wednesday, October 27–28.

Slides: hyeongminlee.github.io/slides/python-programming

← All weeks
01 / 00
Scroll · ↓ · Space