Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lists 01024111 Computers and Programming. Agenda What is a list? How to access elements in the list? The for statement Operations on lists Looping with.

Similar presentations


Presentation on theme: "Lists 01024111 Computers and Programming. Agenda What is a list? How to access elements in the list? The for statement Operations on lists Looping with."— Presentation transcript:

1 Lists 01024111 Computers and Programming

2 Agenda What is a list? How to access elements in the list? The for statement Operations on lists Looping with for statement Examples 2

3 WHAT IS A LIST? 3

4 Test scores for 5 students We can use 5 variables for storing 5 numbers. 4 s1 = 10 s2 = 16 s3 = 15 s4 = 9 s5 = 23 10 16 15 23 9 s1 s2 s3 s5 s4 program 10 16 15 23 9 s1 s2 s3 s5 s4

5 Computing statistics 5 t = 0 t += s1 t += s2 t += s3 t += s4 t += s5 avg = t / 5 m = 0 if s1 > m: m = s1 if s2 > m: m = s2 if s3 > m: m = s3 if s4 > m: m = s4 if s5 > m: m = s5 What is the goal of this program? The summation How about this? The average And this? The maximum

6 Side notes In the last slide, we use a new type of operators: +=. 6 a = a + 1 a += 1 a = a * 2 a *= 2

7 Test scores for 50 students Suppose that now you have 50 students in a class. How can you store all the scores? 7

8 50 variables We can use 50 variables to store 50 numbers 8 s1 = 10 s2 = 16 s3 = 15 s4 = 9 s5 = 23 … … … Extremely difficult to deal with

9 Lists 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 9 23

10 A 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,

11 Examples 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']

12 Example A list of names 12 ["somying", "somsak", "somchai"] "somying" "somsak" "somchai"

13 A 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] 10 16 15 9 9 23 scores

14 ACCESSING ITEMS IN A LIST 14

15 Indexing 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 10 16 15 9 9 23 scores scores[0] scores[1] scores[2] scores[3] scores[4]

16 Accessing items through their indices Recall that the first item has index 0. 16 scores = [10, 16, 15, 9, 23] print(scores[0]) >>> 10 print(scores[3]) >>> 9 print(scores[1] + scores[4]) >>> 39

17 Example 0 1 2 3 4 5 6 17 >>> print(days[3]) wed 'sun' 'mon' 'tue' 'wed' 'thu' 'fri' 'sat' days

18 Thinking 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

19 Thinking Corner: solution 19 a = [1,2,1,4,3,2,4,2,5,6,3,7] i = 0 while i <= 11: print(a[i]) i = i + 1

20 Practice What is the output? 20 ps = [2,3,5,7,11] i = 0 while i<5: print(ps[i]) i = i + 2 2 5 11

21 More practice What is the output? 21 ps = [2,3,5,7,11,13] nn = [1,2,1,1, 2, 1] i = 0 while i<6: print(ps[i]) i = i + nn[i] 2 3 7 11

22 Modifying 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]

23 Practice What is the output? 23 ps = [1,2,1,3,1,4] t = 0 j = 0 while j t: t = ps[j] else: ps[j] = t print(ps[j]) j += 1 122334122334 122334122334

24 Anything goes… A list can hold items with different types. 24 stinfo = ["dang", 20, 167, 78.5] "dang 20 167 78.5 stinfo stinfo[0] stinfo[1] stinfo[2] stinfo[3]

25 An 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 We get an error because we try to access an item which is not there.

26 THE FOR-STATEMENT 26

27 The for statement We can use the for statement to iterate through all items in a list Syntax: 27 for var in list: statement statement For statement controls a block, so make sure you have the same indent.

28 How does the for 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) 2 2 3 3 5 5 7 7 11 x x 2 3 5 7 x x x x x x x x

29 Thinking 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 = 0 for x in a: total = total + x print(total)

30 This helps when processing lists… 30 s = [10,16,15,9,13] t = 0 for x in s: t = t + x m = 0 for x in s: if x > m: x = m Computing the summation Compute the maximum

31 ... even when they contain 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 = 0 for x in s: t = t + x m = 0 for x in s: if x > m: x = m Computing the sum Computing the maximum Nothing changes

32 A quick summary on how to access items in a list 32 Referring to each item a[5] Referring to each item a[5] Iterate through a list for x in a: c += x Iterate through a list for x in a: c += x a a

33 OPERATIONS ON LISTS 33

34 Working with lists Operators on lists List functions Adding items to lists 34

35 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

36 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 Very useful for initializing lists.

37 Example for multiplying with 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]

38 List functions Important functions are 38 namesobjectivesexamplesresults 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

39 Examples 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

40 Appending 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]

41 EXAMPLE 1 41

42 Statistics 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

43 Main 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) total / len(data) max(data) min(data)

44 Thinking 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 x = int(input()) while x!=-1: data.append(x) x = int(input())

45 FOR LOOPS 45

46 for Loops for Loops We can use the for statement to simplify many of the loops written with the while statement. 46 t = 1 for i in [1,2,3,4,5]: t *= i print(t) What is this program doing?

47 Printing 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])

48 Function range 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])

49 Function range Function range returns a result that acts like a list. Its usages are shown below. 49 usagesresult range(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-1 range(3,7) => [3,4,5,6]

50 Quick practice What does this program compute? 50 t = 0 for i in range(100): t += i*i print(t)

51 More quick practice What does this program compute? 51 t = 0 for i in range(200): if i % 3 == 0: t += i print(t)

52 Practice 52 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 step

53 Thinking Corner 53 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

54 Write function count_factors that returns the number of positive integers that divides n using for-statement. Thinking Corner 54 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 range(n + 1): What would happen if we change to this? ZeroDivisionError: integer division or modulo by zero

55 Comparison 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 f = 1 while f <= n: if n % f == 0: count = count+1 f = f + 1 return count

56 Practice 56 def is_prime(n): Use that to write is_prime def 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.

57 EXAMPLE 2 57

58 Counting 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

59 How can we keep vote 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 000000 Does not use For storing vote counts

60 Initialization Everyone starts with 0 votes. 60 scores = [0,0,0,0,0,0] scores = [0] * 6 Much easier to write when we have more candidates.

61 Read and update vote counts 61 scores[choice] += 1 scores = [0] * 6 choice = int(input()) while choice != -1: scores[choice] += 1 choice = int(input())

62 Report 62 show_result(scores) scores = [0] * 6 choice = int(input()) while choice != -1: scores[choice] += 1 choice = int(input()) 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 cnum in range(1,len(s)): print(cnum,"gets",s[cnum],"votes")

63 Thinking 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)) 310310

64 Thinking Corner: solution 64 def freq(ls,x): c = 0 for y in ls: if y == x: c += 1 return c


Download ppt "Lists 01024111 Computers and Programming. Agenda What is a list? How to access elements in the list? The for statement Operations on lists Looping with."

Similar presentations


Ads by Google