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.

Slides:



Advertisements
Similar presentations
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Advertisements

CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Loops (Part 1) Computer Science Erwin High School Fall 2014.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Computer Science 1620 Loops.
1 Python Chapter 4 Branching statements and loops © Samuel Marateck 2010.
SM1205 Interactivity Topic 06: Iteration and Multiple Objects Spring 2010SCM-CityU1.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Lists in Python.
Programming Training Main Points: - Lists / Arrays in Python. - Fundamental algorithms on Arrays.
General Programming Introduction to Computing Science and Programming I.
Python November 28, Unit 9+. Local and Global Variables There are two main types of variables in Python: local and global –The explanation of local and.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Programming for Engineers in Python Sawa 2015 Lecture 2: Lists and Loops 1.
Neal Stublen Computer Memory (Simplified)  Remember, all programming decisions came down to a true or false evaluation  Consider.
Built-in Data Structures in Python An Introduction.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 8 Working.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Loops and Simple Functions CS303E: Elements of Computers and Programming.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Count Controlled Loops (Nested) Ain’t no sunshine when she’s gone …
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Control flow Ruth Anderson UW CSE 160 Spring
Python Programing: An Introduction to Computer Science
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Control flow Ruth Anderson UW CSE 160 Winter
What do I need to Know For My Assignment?. C Pointer Review To declare a pointer, we use the * operator. This is similar to but different from using *
Lecture 14 – lists, for in loops to iterate through the elements of a list COMPSCI 1 1 Principles of Programming.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
13 Arrays CE : Fundamental Programming Techniques June 161.
1 float Data Type Data type that can hold numbers with decimal values – e.g. 3.14, 98.6 Floats can be used to represent many values: –Money (but see warning.
String and Lists Dr. José M. Reyes Álamo.
CSC 211 Java I for loops and arrays.
Introduction to Computing Science and Programming I
CS 115 Lecture 8 Structured Programming; for loops
Programming for Engineers in Python
While Loops in Python.
Lecture 07 More Repetition Richard Gesick.
Collection: Lists Computers and Programming Chaiporn Jaikaeo
Ruth Anderson UW CSE 160 Winter 2017


Chapter 4 LOOPS © Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission.
Lists in Python.
CS190/295 Programming in Python for Life Sciences: Lecture 6
2017 Jan Sun Mon Tue Wed Thu Fri Sat

Ruth Anderson UW CSE 140 Winter 2014
Gantt Chart Enter Year Here Activities Jan Feb Mar Apr May Jun Jul Aug
Programming Training Main Points:
String and Lists Dr. José M. Reyes Álamo.
Remembering lists of values lists
Conditional and iterative statements
Jan Sun Mon Tue Wed Thu Fri Sat
For loops Taken from notes by Dr. Neil Moore
CS 240 – Lecture 7 Boolean Operations, Increment and Decrement Operators, Constant Types, enum Types, Precedence.
Introduction to Programming with Python
Introduction to Computer Science

While Loops in Python.
TIMELINE NAME OF PROJECT Today 2016 Jan Feb Mar Apr May Jun
Introduction to Computer Science
Presentation transcript:

Lists 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 2

WHAT IS A LIST? 3

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

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

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

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

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

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]

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,

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

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

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] scores

ACCESSING ITEMS IN A LIST 14

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 scores[0] scores[1] scores[2] scores[3] scores[4]

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

Example >>> print(days[3]) wed 'sun' 'mon' 'tue' 'wed' 'thu' 'fri' 'sat' days

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

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

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

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]

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]

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 +=

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

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.

THE FOR-STATEMENT 26

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.

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) x x x x x x x x x x

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)

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

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

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

OPERATIONS ON LISTS 33

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

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]

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.

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]

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

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

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]

EXAMPLE 1 41

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

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)

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())

FOR LOOPS 45

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?

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

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

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]

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

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

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

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

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

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

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.

EXAMPLE 2 57

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

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 Does not use For storing vote counts

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.

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

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")

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))

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