Python Programming · Week 7

Lists and Tuples

Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering

This week

The scores are gone

n = int(input("How many scores? "))

total = 0

for i in range(1, n + 1):

score = int(input(f"Score {i}: "))

total += score

print(f"Average: {total / n}")

How many scores? 4

Score 1: 85

Score 2: 72

Score 3: 93

Score 4: 60

Average: 77.5

How many scores are above the average?

after the loop

total310 score60
857293 gone

the loop adds each score, then forgets it · keep them all?

This week

Keep them in a list

n = int(input("How many scores? "))

scores = []

for i in range(1, n + 1):

score = int(input(f"Score {i}: "))

scores.append(score)

average = sum(scores) / len(scores)

above = 0

for score in scores:

if score > average:

above += 1

print(f"Scores: {sorted(scores)}")

print(f"Average: {average}")

print(f"Highest: {max(scores)}, lowest: {min(scores)}")

print(f"Above the average: {above}")

←an empty list

←one more item each time

←every score again, after the loop

←built-in functions for lists

How many scores? 4

Score 1: 85

Score 2: 72

Score 3: 93

Score 4: 60

Scores: [60, 72, 85, 93]

Average: 77.5

Highest: 93, lowest: 60

Above the average: 2

a list: many values in one variable · use them again, any time

Lists

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

Lists

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
Lists

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

Lists

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

Strings

A string works the same way

index 012345 Python from the end -6-5-4-3-2-1

>>>word = "Python"

>>>word[0]

'P'quotes: a string

>>>word[-1]

'n'

>>>word[0:3]

'Pyt'

>>>word[::-1]

'nohtyP'

>>>len(word)

6

a string: characters in order · the same indexes, the same slices

Lists

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

Strings

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'

immutable

cannot be changed

to keep the new string: store it

a string is immutable · a string method returns a new string

Strings

String methods

>>>" hi ".strip()

'hi'

spaces off both ends

>>>"Hello".lower()

'hello'

lowercase

>>>"hello".upper()

'HELLO'

uppercase

>>>"2026".isdigit()

True

only digits?

>>>"20a6".isdigit()

False

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

True

starts with ...?

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

True

ends with ...?

Loops

for, item by item

scores = [85, 72, 93, 60]

scores → 85729360 the items, in order
range(4) → 0123 week 5: the numbers, in order

for score in scores:score = 85score = 72score = 93score = 60

print(score)

85

72

93

60

no more items: the loop ends

the loop variable takes the items in turn · range gives numbers, a list gives its items

Loops

A string, and the positions

scores = [85, 72, 93, 60]

a string

for ch in "hi!":

print(ch)

h

i

!

positions

for i in range(len(scores)):

print(f"{i}: {scores[i]}")

0: 85

1: 72

2: 93

3: 60

a string: one character at a time · range(len(...)): when you need the positions

Lists and strings

in: is it there?

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

>>>85 in scores

True

>>>70 in scores

False

>>>"@" in "kim@seoultech.ac.kr"

True

>>>"z" in "hello"

False

x in items: True or False · for a list, and for a string

Built-in functions

Functions for lists

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

>>>len(scores)

4

how many

>>>sum(scores)

310

the total

>>>min(scores)

60

the smallest

>>>max(scores)

93

the largest

>>>sorted(scores)

[60, 72, 85, 93]

a new list, sorted

>>>scores

[85, 72, 93, 60]

unchanged

len, sum, min, max · sorted: a new list, the old one unchanged

Built-in functions

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

Strings and lists

split, join, replace

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

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

a string → a list

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

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

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

'Kim, Lee, Park'

a list → a string

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

'010 1234 5678'

the pieces are strings: '85', not 85

split: a string into a list · join: a list into a string

Lists

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

Lists

A copy: a new list

a = [10, 20, 30]

c = a.copy()

c[0] = c[0] + 1

print(c[0])

print(a[0])

11

?10

a 102030 .copy() c 102030 a new list 11

.copy(): a new list · a change to one leaves the other as it is

Lists

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

Tuples

A tuple

>>>point = (3, 4)

>>>point[0]

3

>>>len(point)

2

>>>point[0] = 5

TypeError: 'tuple' object does not support item assignment

immutable

like a string

a tuple: values in parentheses · fixed, it cannot change

Tuples

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

Tuples

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

Tuples

Fibonacci in one line

1
1
2
3 a
5 b a
8 b
13
…

week 5

a = 3

b = 5

c = a + b

a = b

b = c

unpacking

a = 3

b = 5

a, b = b, a + b

a, b = b, a + b the right side first

↓

a, b = 5, 3 + 5 the old values

↓

a, b = (5, 8) a tuple

↓

a = 5b = 8 one value each

the right side uses the old a and b · no c needed

Tuples

Returning two values

def min_max(scores):

return min(scores), max(scores)

print(min_max([85, 72, 93, 60]))

low, high = min_max([85, 72, 93, 60])

print(f"{low} {high}")

(60, 93)

60 93

return 60, 93 inside the call

↓

print((60, 93)) the call's value: a tuple
low, high = (60, 93) the call's value

↓

low = 60high = 93 one value each

return a, b: one tuple · unpack it at the call

Tuples

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

This week

The whole program

n = int(input("How many scores? "))

scores = []

for i in range(1, n + 1):

score = int(input(f"Score {i}: "))

scores.append(score)

average = sum(scores) / len(scores)

above = 0

for score in scores:

if score > average:

above += 1

print(f"Scores: {sorted(scores)}")

print(f"Average: {average}")

print(f"Highest: {max(scores)}, lowest: {min(scores)}")

print(f"Above the average: {above}")

←[]: an empty list

←append: one more item

←sum, len

←for over the list: the scores again

←sorted, max, min

a list keeps the values · use them again, as often as you need

Next steps

Next: the practice video.

Have Python open. Type everything with me.

See you in class.

← All weeks
01 / 00
Scroll · ↓ · Space