0% found this document useful (0 votes)
2 views5 pages

Concept: Think Python, Ch. 10

This document is a lesson plan for teaching Python coding, focusing on the List data structure and looping statements. It covers how to define and manipulate lists, including common operations like append, remove, and sorting, as well as the concept of references in Python. Additionally, it includes an exercise requiring students to analyze temperature data using loops and lists.

Uploaded by

EricXIze
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views5 pages

Concept: Think Python, Ch. 10

This document is a lesson plan for teaching Python coding, focusing on the List data structure and looping statements. It covers how to define and manipulate lists, including common operations like append, remove, and sorting, as well as the concept of references in Python. Additionally, it includes an exercise requiring students to analyze temperature data using loops and lists.

Uploaded by

EricXIze
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

F.

3 Computer Literacy
Python coding - Lesson 4

Objectives:
● Learn how to use List data structure.
● Apply looping statements to process data in the list.

Ref: Think Python, Ch. 10

Concept
Lists in Python are similar to Lists in App Inventor. They can be used to
store a collection of values. Something like a cabinet with many drawers.
Each drawer is storing a value.

Unlike many other programming languages, different types of values can be


stored into the same list. (But very often a list holds values of the same type)

The basic syntax is using square brackets [ ] to denote a list, with elements
separated by comma.

e.g.
a = [ 1, 2, "Hello!", True, 5.2 ]
b = [ ] # b is an empty list

Task 1
Define lists a and b as shown above. Try the following print() functions:
(i) print( a ), i.e. to print the whole list;
(ii) print( len( a ) )
(iii) print( a[2] )
What are the meanings of len( a ) and a[2] ?
What happens if you try to print a[5] ?

The expression a[i] is accessing the (i+1)th element of a list.


The value i is called the index of the element within the list.
Common operations on list
List data structures are mutable. i.e. Its content can be changed.

Task 2: Try the following operations to mutate a list.


● Change the values stored in a list
e.g.
a = [1, 2, 3, 4, 5]
a[2] = 6 # [2] is an indexing operation on the list

Since each element of a list can be changed, essentially you have a list of 5 variables 𝑎0, 𝑎1, 𝑎2, 𝑎3, 𝑎4.

● append / extend / remove / insert / reverse


e.g.

a = [1, 2, 3, 4, 5]
a.append(6) # add single element
print(a) # >>> [1,2,3,4,5,6]

b = [2, 3, 9]
a.extend(b) # add multiple elements
print(a) # >>> [1,2,3,4,5,6,2,3,9]

e = a.pop() # get and remove the last element


print(e) # >>> 9
print(a) # >>> [1,2,3,4,5,6,2,3]

a.reverse()
print(a) # >>> [3,2,6,5,4,3,2,1]

a.insert(2,777) # insert into a[2], pushing the rest to right


print(a) # >>> [3,2,777,6,5,4,3,2,1]

a.remove(2) # remove the first occurrence of 2


print(a) # >>> [3,777,6,5,4,3,2,1]

print(a.index(6)) # >>> 2 (index of element 6 in list a)

a.sort() # sort in ascending order


print(a) # >>> [1,2,3,3,4,5,6,777]

a.sort(reverse=True) # sort in descending order

# Note: for .remove() and .index(), it is an error


# if the element is not inside the list.

The above operations except a.index(??) are destructive operations. It changes the list involved.
Which of the above operations give output besides changing the lists involved?
Sometimes we want the results of modifications, but at the same time do not want to modify the
original list.
Task 3
Try the following methods, which create a new list as results, keeping the original lists unchanged.

● extend / append
a = [1, 2, 3, 4]
b = [5, 6, 7]
c = a + b # c is [1,2,3,4,5,6,7]; a and b unchanged

● slicing
d = c[2:5] # same as d = [ c[2], c[3], c[4] ]
d = c[:] # same as d = c[0:len(c)] i.e. the whole list
d = c[:-1] # without the last element
d = c[1:] # without the first

!!! Assignment involving lists !!!

With simple data types like integer, float, etc, values are copied from one variable to another during
assignment. The two variables are independent of each other:

a = 1
b = a # value of a is copied to b
b = 2 # changing b has no effect on a as expected

With aggregate data types (List, Dictionary (in the next lesson), Object (in the second term)), the
values are NOT copied during assignment. The two variables are actually referencing the same
location in memory (we say a "reference" is copied)

a = [1, 2, 3]
b = a # b and a refer to the SAME list
b[1] = 999 # modify b
print(a) # >>> [1, 999, 3] a is changed!
b = [4, 5, 6] # assigning another list to b
# is changing it to refer to another location
# (just re-binds variable b to another location)
print(a) # >>> [1, 999, 3] does not change a

Be very careful when assigning one list variable to another. If you do not want to modify the original
list, just make a copy by using the slicing [:] operator.

a = [1, 2, 3]
b = a[:] # The slicing operation is making a new list
b[1] = 999 # changing b does not affect a
print(a) # >>> [1, 2, 3]
Process the whole list with for-loop

e.g. using the index to access the elements one-by-one

a = [23, 45, 67, 98, 12]

for i in range(len(a)):
a[i] += i # increase each element by its index

print(a) # >>> [23, 46, 69, 101, 16]

If it is not required to modify the elements, just use for-in loop directly on the list.

e.g. printing elements that are even numbers

a = [23, 45, 67, 98, 12]


for x in a:
if (x % 2 == 0):
print(x) # prints 98 and 12 on two lines

If both the values of elements and their indexes are needed, use enumerate()

for i, x in enumerate( a ):
print( f"Item #{i}: {x}" ) # using format-string

Exercise

Construct a program for the following requirements. Name your program file in the format

ex4_class_class no.py

with your actual class and class no e.g. ex4_3A_05.py for class 3A no. 5.
Compress your file to .zip format and submit it on eClass.

Requirements:

You are given a list of air temperature in different regions of Hong Kong as follows: (download
air_temp.txt and copy the data into your python program code)

# a list of air temperature in different regions (in degrees celsius)


T = [ 19.6, 18.7, 18.8, 20.1, 19.6, 19.6, 19.6, 18.2,
18.3, 18.5, 18.8, 18.8, 13.5, 17.9, 19.7, 19.1,
19, 19.3, 19.1, 18.7, 18.9, 19.7, 18.3, 18.6,
18.1, 12.8, 19, 13.6, 16, 18.4, 19.6, 17.6,
19.4, 19.7, 19.9, 19.2, 19.7, 18.6, 19.1]
Write Python code to
● Count the total number of regions.
● Count the number of regions with a temperature above 18.5 oC.
● Calculate the average temperature over all regions.

Note: You are expected to use appropriately for loop to help you count or calculate in the above
tasks. Do not get the answers from direct or immediate ways.

Sample output: (underlined numbers are calculated with Python code)

The total number of regions: 39


Number of regions with temperature above 18.5 degC: 27
Average temperature: 18.49

Note that you can use the round(b,2) function to round off a float-value b to 2 decimal places.

You might also like