1 / 64

Lists

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 for statement Examples. What is a List?. Test scores for 5 students. We can use 5 variables for storing 5 numbers.

ahava
Download Presentation

Lists

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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

  3. What is a List?

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

  5. Computing statistics And this? The maximum t = 0t += s1t += s2t += s3t += s4t += 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? The summation The average avg = t / 5 How about this?

  6. Side notes • In the last slide, we use a new type of operators: +=. 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?

  8. 50 variables • We can use 50 variables to store 50 numbers s1 = 10s2 = 16s3 = 15s4 = 9s5 = 23……… Extremelydifficultto 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: [10, 16, 15, 9, 23] 10 16 15 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.

  11. Examples • A list of numbers of days for each month [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 ["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. scores = [10, 16, 15, 9, 23] scores 10 16 15 9 23

  14. Accessing items in a list

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

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

  17. Example >>> print(days[3]) days wed

  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.

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

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

  21. More practice • What is the output? 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

  22. Modifying data in a list • As we can refer to items in the list, we can assign new values to them. >>> 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? 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

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

  25. An Empty List • An empty list is also a list >>> 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

  27. The for statement • We can use the for statement to iterate through all items in a list • Syntax: forvarinlist:statementstatement 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. forx in [2,3,5,7,11]: print(x) 2 3 2 x x x x x 5 3 7 5 11 7 11

  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] a = [1,2,1,4,3,2,4,2,5,6,3,7]total = 0for x in a: total = total + xprint(total)

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

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

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

  33. Operations on Lists

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

  35. Operators on lists (1) • We can add two lists. The result is the concatenation of the two lists. >>> [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. >>> [1,2] * 3[1,2,1,2,1,2] 1 Very useful for initializing lists. 2

  37. Example for multiplying with an integer • If we want to create a list with 10 items all of them are zero. >>> [0] * 10[0,0,0,0,0,0,0,0,0,0]

  38. List functions • Important functions are

  39. Examples of usage >>> 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. >>> s = [1,2,5]>>> s.append(10)>>> s[1,2,5,10]

  41. Example 1

  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.

  43. Main program 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. 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

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

  47. Printing 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 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.

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

More Related