Post on 02-Jan-2016
ListsLists
01024111 Computers and Programming
AgendaAgenda
• What is a list?• How to access elements in the list?• The for statement• Operations on lists• Looping with for statement• Examples
2
WHAT IS A LIST?WHAT IS A LIST?
3
Test scores for 5 Test scores for 5 studentsstudents
• We can use 5 variables for storing 5 numbers.
4
s1 = 10s2 = 16s3 = 15s4 = 9s5 = 23
s1 = 10s2 = 16s3 = 15s4 = 9s5 = 23
101615
239
s1s2s3
s5s4
program
101615
239
s1s2s3
s5s4
Computing statisticsComputing statistics
5
t = 0t += s1t += s2t += s3t += s4t += s5
t = 0t += s1t += s2t += s3t += s4t += s5
avg = t / 5avg = t / 5
m = 0if s1 > m: m = s1if s2 > m: m = s2if s3 > m: m = s3if s4 > m: m = s4if s5 > m: m = s5
m = 0if s1 > m: m = s1if s2 > m: m = s2if s3 > m: m = s3if s4 > m: m = s4if s5 > m: m = s5
What is the goalof this program?What is the goalof this program?
The summationThe summation
How about this?How about this?
The averageThe average
And this?And this?The maximumThe maximum
Side notesSide notes
• In the last slide, we use a new type of operators: +=.
6
a = a + 1a = a + 1 a += 1a += 1
a = a * 2a = a * 2 a *= 2a *= 2
Test scores for 50 Test scores for 50 studentsstudents
• Suppose that now you have 50 students in a class.
• How can you store all the scores?
7
50 variables50 variables
• We can use 50 variables to store 50 numbers
8
s1 = 10s2 = 16s3 = 15s4 = 9s5 = 23………
s1 = 10s2 = 16s3 = 15s4 = 9s5 = 23………
Extremelydifficult
to deal with
ListsLists
• In Python, we have data types that can keep many items in one place. One of these is a list.
• An example of a list:
9
[10, 16, 15, 9, 23][10, 16, 15, 9, 23]
101016161515992323
A list constantA list constant
• We write a list by enclosing all items in a pair of brackets [ ], with a comma (,) separating each pair of items.
• It is OK to have extra comma after the last item.
10
,
ExamplesExamples
11
• A list of numbers of days for each month
[31,28,31,30,31,30,
31,31,30,31,30,31]
[31,28,31,30,31,30,
31,31,30,31,30,31]
• A list of names of days in a week
['sun','mon','tue','wed', 'thu','fri','sat'] ['sun','mon','tue','wed', 'thu','fri','sat']
ExampleExample
• A list of names
12
["somying", "somsak", "somchai"]["somying", "somsak", "somchai"]
"somying""somying""somsak""somsak""somchai""somchai"
A list is just another dataA list is just another data
• We can assign a list to a variable. That variable will refer to that list.
13
scores = [10, 16, 15, 9, 23]scores = [10, 16, 15, 9, 23]
101016161515992323
scoresscores
ACCESSING ITEMS IN A ACCESSING ITEMS IN A LISTLIST
14
IndexingIndexing
• We can refer to an item in a list by specifying its index in the list.
• The first item in the list has index 0; the next one has index 1, and so on.
15
101016161515992323
scoresscores scores[0]scores[0]scores[1]scores[1]scores[2]scores[2]scores[3]scores[3]scores[4]scores[4]
Accessing items through Accessing items through their indicestheir indices
• Recall that the first item has index 0.
16
scores = [10, 16, 15, 9, 23]scores = [10, 16, 15, 9, 23]
print(scores[0])print(scores[0])
>>> 10>>> 10
print(scores[3])print(scores[3])
>>> 9>>> 9
print(scores[1] + scores[4])print(scores[1] + scores[4])
>>> 39>>> 39
ExampleExample
0
1
2
3
4
5
6
17
>>> print(days[3])>>> print(days[3])
wed'sun'
'mon'
'tue'
'wed'
'thu'
'fri'
'sat'
daysdays
Thinking CornerThinking Corner
• Write a program that print all items in the following list a. You are not allowed to write "print" more than once.
a = [1,2,1,4,3,2,4,2,5,6,3,7]
• Note: there are 12 items in the list.• Hint: try using the while statement.
18
Thinking Corner: solutionThinking Corner: solution
19
a = [1,2,1,4,3,2,4,2,5,6,3,7]i = 0while i <= 11: print(a[i]) i = i + 1
a = [1,2,1,4,3,2,4,2,5,6,3,7]i = 0while i <= 11: print(a[i]) i = i + 1
PracticePractice
• What is the output?
20
ps = [2,3,5,7,11]i = 0while i<5: print(ps[i]) i = i + 2
ps = [2,3,5,7,11]i = 0while i<5: print(ps[i]) i = i + 2
2511
2511
More practiceMore practice
• What is the output?
21
ps = [2,3,5,7,11,13]nn = [1,2,1,1, 2, 1]i = 0while i<6: print(ps[i]) i = i + nn[i]
ps = [2,3,5,7,11,13]nn = [1,2,1,1, 2, 1]i = 0while i<6: print(ps[i]) i = i + nn[i]
23711
23711
Modifying data in a listModifying data in a list
• As we can refer to items in the list, we can assign new values to them.
22
>>> s = [10,20,30,40,50]>>> s[2] = 5>>> s[10,20,5,40,50]>>> s[4] += 7>>> s[10,20,5,40,57]
>>> s = [10,20,30,40,50]>>> s[2] = 5>>> s[10,20,5,40,50]>>> s[4] += 7>>> s[10,20,5,40,57]
PracticePractice
• What is the output?
23
ps = [1,2,1,3,1,4]t = 0j = 0while j < 6: if ps[j] > t: t = ps[j] else: ps[j] = t print(ps[j]) j += 1
ps = [1,2,1,3,1,4]t = 0j = 0while j < 6: if ps[j] > t: t = ps[j] else: ps[j] = t print(ps[j]) j += 1
122334
122334
Anything goes…Anything goes…
• A list can hold items with different types.
24
stinfo = ["dang", 20, 167, 78.5]stinfo = ["dang", 20, 167, 78.5]
"dang"dang202016716778.578.5
stinfostinfo stinfo[0]stinfo[0]stinfo[1]stinfo[1]stinfo[2]stinfo[2]stinfo[3]stinfo[3]
An Empty ListAn Empty List
• An empty list is also a list
25
>>> mylist = []>>> a = mylist[0]Traceback (most recent call last): builtins.IndexError: list index out of range
>>> mylist = []>>> a = mylist[0]Traceback (most recent call last): builtins.IndexError: list index out of range
We get an error because we try to access an item which is not there.
THE FOR-STATEMENTTHE FOR-STATEMENT
26
The The for for statementstatement
• We can use the for statement to iterate through all items in a list
• Syntax:
27
for var in list: statement statement
for var in list: statement statement
For statement controls a block, so make sure you have the same indent.
How does the for How does the for statement work?statement work?
• The block inside the for statement is executed as the variable iteratively refers to each item in the list.
28
for x in [2,3,5,7,11]: print(x)for x in [2,3,5,7,11]: print(x)
223355771111
xx
235711
xxxxxxxx
Thinking CornerThinking Corner
• Write a program that computes the summation of all items in the following list.
a = [1,2,1,4,3,2,4,2,5,6,3,7]
29
a = [1,2,1,4,3,2,4,2,5,6,3,7]total = 0for x in a: total = total + xprint(total)
a = [1,2,1,4,3,2,4,2,5,6,3,7]total = 0for x in a: total = total + xprint(total)
This helps when This helps when processing lists…processing lists…
30
s = [10,16,15,9,13]t = 0for x in s: t = t + x
s = [10,16,15,9,13]t = 0for x in s: t = t + x
m = 0for x in s: if x > m: x = m
m = 0for x in s: if x > m: x = m
Computingthe
summation
Computingthe
summation
Computethe
maximum
Computethe
maximum
...... even when they even when they contain lots of datacontain lots of data
31
s = [10,16,15,9,13,20,12,11,2,14, 6,7,13,4,6,7,14,18,9,12]t = 0for x in s: t = t + x
s = [10,16,15,9,13,20,12,11,2,14, 6,7,13,4,6,7,14,18,9,12]t = 0for x in s: t = t + x
m = 0for x in s: if x > m: x = m
m = 0for x in s: if x > m: x = m
Computing the sumComputing the sum
Computing the maximumComputing the maximum
Nothing changesNothing changes
A quick summary on how A quick summary on how to access items in a listto access items in a list
32
Referring to each item
a[5]
Iterate through a list
for x in a: c += xa a
OPERATIONS ON LISTSOPERATIONS ON LISTS
33
Working with listsWorking with lists
• Operators on lists• List functions• Adding items to lists
34
Operators on lists (1)Operators on lists (1)
• We can add two lists. The result is the concatenation of the two lists.
35
>>> [1,2] + [5,10,15][1,2,5,10,15]>>> [1,2] + [5,10,15][1,2,5,10,15]
12
51015
Operators on lists (2)Operators on lists (2)
• We can multiply a list with an integer. The result is the concatenation of copies of the original list.
36
>>> [1,2] * 3[1,2,1,2,1,2]>>> [1,2] * 3[1,2,1,2,1,2]
12 Very useful
for initializing lists.
Very useful for initializing lists.
Example for multiplying Example for multiplying with an integerwith an integer
• If we want to create a list with 10 items all of them are zero.
37
>>> [0] * 10[0,0,0,0,0,0,0,0,0,0]>>> [0] * 10[0,0,0,0,0,0,0,0,0,0]
List functionsList functions
• Important functions are
38
names objectives examples results
len Returns the number of items
len([1,2,5]) 3
sum Returns the summation
sum([1,2,5]) 8
max Returns the maximum
max([1,2,5]) 5
min Returns the minimum
min([1,2,5]) 1
Examples of usageExamples of usage
39
>>> len([])0>>> s = [1,2] + [3,5,10]>>> sum(s)21>>> max(s)10>>> len(s)5>>> len(s + [1,6]) #=>[1,2,3,5,10,1,6]7
>>> len([])0>>> s = [1,2] + [3,5,10]>>> sum(s)21>>> max(s)10>>> len(s)5>>> len(s + [1,6]) #=>[1,2,3,5,10,1,6]7
Appending to listsAppending to lists
• We can add items to lists by using method append as shown below.
40
>>> s = [1,2,5]>>> s.append(10)>>> s[1,2,5,10]
>>> s = [1,2,5]>>> s.append(10)>>> s[1,2,5,10]
EXAMPLE 1EXAMPLE 1
41
StatisticsStatistics
• We shall write a program that computes data statistics The program reads data items from the
user until the user enter -1 Then the program reports the
summation, the average, the maximum, and the minimum.
42
Main programMain program
43
data = read_input() # read data as a list
total = _____________________
average = ___________________
max = _______________________
min = _______________________
# display output
data = read_input() # read data as a list
total = _____________________
average = ___________________
max = _______________________
min = _______________________
# display output
sum(data)sum(data)
total / len(data)total / len(data)
max(data)max(data)
min(data)min(data)
Thinking CornerThinking Corner
• Write function read_list that reads integers from the user until the user enters -1, and returns a list of the integers.
44
def read_list(): print("Enter list (-1 to end):") data = []
return data
def read_list(): print("Enter list (-1 to end):") data = []
return data
x = int(input()) while x!=-1: data.append(x) x = int(input())
x = int(input()) while x!=-1: data.append(x) x = int(input())
FOR LOOPSFOR LOOPS
45
for Loopsfor Loops
• We can use the for statement to simplify many of the loops written with the while statement.
46
t = 1for i in [1,2,3,4,5]: t *= iprint(t)
t = 1for i in [1,2,3,4,5]: t *= iprint(t)
What is this program doing?
PrintingPrinting
47
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dev']days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for i in [0,1,2,3,4,5,6,7,8,9,10,11]: print(months[i],days[i])
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dev']days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for i in [0,1,2,3,4,5,6,7,8,9,10,11]: print(months[i],days[i])
Function Function rangerange
48
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dev']days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for i in range(12): print(months[i],days[i])
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dev']days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for i in range(12): print(months[i],days[i])
Function Function rangerange
• Function range returns a result that acts like a list. Its usages are shown below.
49
usages resultrange(r) a list from 0 to r-1
range(7) => [0,1,2,3,4,5,6]
range(a,b) a list from a to b-1range(3,7) => [3,4,5,6]
Quick practiceQuick practice
• What does this program compute?
50
t = 0for i in range(100): t += i*iprint(t)
t = 0for i in range(100): t += i*iprint(t)
More quick practiceMore quick practice
• What does this program compute?
51
t = 0for i in range(200): if i % 3 == 0: t += iprint(t)
t = 0for i in range(200): if i % 3 == 0: t += iprint(t)
PracticePractice
52
def is_prime(n):def is_prime(n):
Prime numbers are positive integers having exactly two positive factors.
Write function is_prime that returns True if and only if n is a prime number.
Let's do it step by stepLet's do it step by step
Thinking CornerThinking Corner
53
def count_factors(n):def count_factors(n):
Write function count_factors that returns the number of positive integers that divides n using for-statement.
def count_factors(n): count = 0 for f in range(1, n + 1): if n % f == 0: count += 1 return count
def count_factors(n): count = 0 for f in range(1, n + 1): if n % f == 0: count += 1 return count
Write function count_factors that returns the number of positive integers that divides n using for-statement.
Thinking CornerThinking Corner
54
def count_factors(n):def count_factors(n):def count_factors(n): count = 0 for f in range(1, n + 1): if n % f == 0: count += 1 return count
def count_factors(n): count = 0 for f in range(1, n + 1): if n % f == 0: count += 1 return count
range(n + 1):
What would happen if we change to this?What would happen if we change to this?
ZeroDivisionError: integer division or modulo by zero
ComparisonComparison
55
def count_factors(n): count = 0 for f in range(1, n+1): if n % f == 0: count = count + 1 return count
def count_factors(n): count = 0 for f in range(1, n+1): if n % f == 0: count = count + 1 return count
def count_factors(n): count = 0 f = 1 while f <= n: if n % f == 0: count = count+1 f = f + 1 return count
def count_factors(n): count = 0 f = 1 while f <= n: if n % f == 0: count = count+1 f = f + 1 return count
PracticePractice
56
def is_prime(n):def is_prime(n):
Use that to write is_primeUse that to write is_prime
def is_prime(n): return count_factors(n)==2def is_prime(n): return count_factors(n)==2
Prime numbers are positive integers having exactly two positive factors.
Write function is_prime that returns True if and only if n is a prime number.
EXAMPLE 2EXAMPLE 2
57
Counting votesCounting votes
• In one election for student representatives, there are 5 candidates, numbers from 1 to 5.
• Write a program that reads a list of votes and then finds out who wins the election.
58
How can we keep vote How can we keep vote counts?counts?
• Since we have 5 candidates, we will use a list that can keep 5 items.
• However, because the candidate numbers start with 1, we will actually use a list with 6 items so that we can access items with indices 1 to 5.
59
0 0 0 0 0 0
Does not useDoes not use
For storing vote countsFor storing vote counts
InitializationInitialization
• Everyone starts with 0 votes.
60
scores = [0,0,0,0,0,0]scores = [0,0,0,0,0,0]scores = [0] * 6scores = [0] * 6 Much easier
to write when we
have more candidates.
Much easier to write when we
have more candidates.
Read and update vote Read and update vote countscounts
61
scores = [0] * 6choice = int(input())while choice != -1: scores[choice] += 1 scores[choice] += 1 choice = int(input())
scores = [0] * 6choice = int(input())while choice != -1: scores[choice] += 1 scores[choice] += 1 choice = int(input())
ReportReport
62
scores = [0] * 6choice = int(input())while choice != -1: scores[choice] += 1 choice = int(input())show_result(scores)show_result(scores)
scores = [0] * 6choice = int(input())while choice != -1: scores[choice] += 1 choice = int(input())show_result(scores)show_result(scores)
def show_result(s): for i in range(5): cnum = i + 1 print(cnum,"gets",s[cnum],"votes")
def show_result(s): for i in range(5): cnum = i + 1 print(cnum,"gets",s[cnum],"votes")
def show_result(s): for cnum in range(1,len(s)): print(cnum,"gets",s[cnum],"votes")
def show_result(s): for cnum in range(1,len(s)): print(cnum,"gets",s[cnum],"votes")
Thinking CornerThinking Corner
• Write function freq(ls,x) that accepts list ls and a item x, and returns the number of times item x appears in the list.
• Example of usage:
63
a = [1,2,1,1]print(freq(a,1))print(freq(a,2))print(freq(a,3))
a = [1,2,1,1]print(freq(a,1))print(freq(a,2))print(freq(a,3))
310
Thinking Corner: solutionThinking Corner: solution
64
def freq(ls,x): c = 0 for y in ls: if y == x: c += 1 return c
def freq(ls,x): c = 0 for y in ls: if y == x: c += 1 return c