Lecture 14 – lists, for in loops to iterate through the elements of a list COMPSCI 1 1 Principles of Programming.

Slides:



Advertisements
Similar presentations
Lecture 07 – Iterating through a list of numbers.
Advertisements

Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 15 Tuples 5/02/09 Python Mini-Course: Day 4 – Lesson 15 1.
Lists CMSC 201. Overview Today we will learn about: For loops.
Lecture 12 – Loops – while loops COMPSCI 1 1 Principles of Programming.
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.
Lists Introduction to Computing Science and Programming I.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Main task -write me a program
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Lecture 23 – Python dictionaries 1 COMPSCI 101 Principles of Programming.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Lecture 11 – if … else, if... elif statements, nested ifs COMPSCI 1 1 Principles of Programming.
Guide to Programming with Python
Lecture 13 – range function, for…in loops COMPSCI 1 1 Principles of Programming.
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Lists in Python.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
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.
CS1022 Computer Programming & Principles Lecture 1.2 A brief introduction to Python.
Introduction. 2COMPSCI Computer Science Fundamentals.
Lecture 20 – Test revision COMPSCI 101 Principles of Programming.
COMPSCI 101 Principles of Programming Lecture 4 –The type() function, the string type, the len() function, string slices.
Lecture 21 - Tuples COMPSCI 101 Principles of Programming.
If statements while loop for loop
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Last Week if statement print statement input builtin function strings and methods for loop.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Lecture 19 - More on Lists, Slicing Lists, List Functions COMPSCI 101 Principles of Programming.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
Loops & List Intro2CS – week 3 1. Loops -- Motivation Sometimes we want to repeat a certain set of instructions more than once. The number of repetitions.
For Loops CMSC 201. Overview Today we will learn about: For loops.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
Lecture 15 – more on lists and for…in loops, the split() function COMPSCI 1 1 Principles of Programming.
Last Week Modules Save functions to a file, e.g., filename.py The file filename.py is a module We can use the functions in filename.py by importing it.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 10 Lists 1.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
CMPT 120 Topic: Searching – Part 2 and Intro to Time Complexity (Algorithm Analysis)
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.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
String and Lists Dr. José M. Reyes Álamo.
COMPSCI 107 Computer Science Fundamentals
CS1022 Computer Programming & Principles
Generating Random Numbers
Tuples and Lists.
Chapter 10 Lists.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Chapter 10 Lists.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
String and Lists Dr. José M. Reyes Álamo.
CMSC201 Computer Science I for Majors Lecture 08 – For Loops
Intro to Computer Science CS1510 Dr. Sarah Diesburg
15-110: Principles of Computing
Python Basics with Jupyter Notebook
Topics Basic String Operations String Slicing
CMSC201 Computer Science I for Majors Lecture 16 – Tuples
Topics Basic String Operations String Slicing
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Topics Basic String Operations String Slicing
Presentation transcript:

Lecture 14 – lists, for in loops to iterate through the elements of a list COMPSCI 1 1 Principles of Programming

 At the end of this lecture, students should be able to:  create a new list  obtain the length of a list  the + operator is used to concatenate lists  the in operator is used to check if an element is in the list  iterate through a list using a for…in loop  perform calculations on the elements of a list Learning outcomes 2Slide

Recap  From lecture 13  the Python range() function is used to define a sequence of values  a for…in loop can be used to implement counter-controlled repetition def get_dice_throws_results(num_dice_throws, num_to_check): count = 0 for i in range(num_dice_throws): dice = random.randrange(1, 7) if dice == num_to_check: count += 1 return count def main(): print(get_dice_throws_results(30000, 6), "sixes thrown (out of throws)") print(get_dice_throws_results(6, 6), "sixes thrown (out of 6 throws)") print(get_dice_throws_results(600000, 6), "sixes thrown (out of throws)") main() def get_dice_throws_results(num_dice_throws, num_to_check): count = 0 for i in range(num_dice_throws): dice = random.randrange(1, 7) if dice == num_to_check: count += 1 return count def main(): print(get_dice_throws_results(30000, 6), "sixes thrown (out of throws)") print(get_dice_throws_results(6, 6), "sixes thrown (out of 6 throws)") print(get_dice_throws_results(600000, 6), "sixes thrown (out of throws)") main() 3Slide 4947 sixes thrown (out of throws) 1 sixes thrown (out of 6 throws) sixes thrown (out of throws)

Why lists?  Let's say we want to store the bank balance amount for every student in this class.  To calculate the total of the first four bank balances?  To calculate the total of all the bank balances? 4Slide bank01 = 2000; bank02 = 231; bank03 = 21; bank04 = -3000; …. bank01 = 2000; bank02 = 231; bank03 = 21; bank04 = -3000; …. How awkward! total = bank01 + bank02 + bank03 + bank04 total = bank01 + bank02 + bank03 + bank04 + bank05 + bank06 + … total = bank01 + bank02 + bank03 + bank04 + bank05 + bank06 + …

The list data structure  A list is a sequence of variables (called elements of the list).  Each element of a list has an index number. The index number always starts at 0.  Each element of a list can be accessed using its index number.  An analagy: 5Slide many_homes[0], many_homes[1], many_homes[2], … single_home 8172 Green St3 / 156 Green St A structure with many variablesA simple variable

Visualising a list data structure  A list can be visualised:  The elements of a list can be of any type, e.g.,  In reality, each element of a list is a reference (see the two diagrams below): 6Slide 012…012… … … or 012…012… "first" 21.5 True … 012…012… … … 012…012… … "first" 21.5 True …

List - Square brackets  Notation using square brackets is used with lists. For example, for the following list (named my_list ), the element at position 1 in the list can be referred to as my_list[1], the first element (at position 0 in the list) can be referred to as my_list[0], and so on. 7Slide 012…012… … my_list

Creating a list in Python  Use square brackets to create a list containing elements. Each element is separated from the next element using a comma, e.g.,  An empty list (contains no elements) can be created:  Another way to create an empty list is: 8Slide my_list my_list = [12, 21, 34] my_list = [] my_list = list() Note that list is a special word in Python. It refers to the list data structure and it should not be used as a variable name.

Printing a list, the length of a list  Lists can be printed using the print() function:  The length of a list is the number of elements currently in the list. The function len() can be used to obtain the current length of a list, e.g., 9Slide my_list = [5, 2, 7, 4, 3, 8, 0, 1, 9, 6, -3] list1 = [] list2 = ['Try', 'something', 'new'] print(my_list) print(list1) print(list2) my_list = [5, 2, 7, 4, 3, 8, 0, 1, 9, 6, -3] list1 = [] list2 = ['Try', 'something', 'new'] print(my_list) print(list1) print(list2) #Continuing from the code above number_of_elements = len(my_list) print(number_of_elements) print(len(list1)) print(len(list2)) #Continuing from the code above number_of_elements = len(my_list) print(number_of_elements) print(len(list1)) print(len(list2)) [5, 2, 7, 4, 3, 8, 0, 1, 9, 6, -3] [] ['Try', 'something', 'new']

Concatenating lists  The + operator can be used to concatenate (join) two lists. Concatenation adds the elements of the second list to the end of the first list, e.g., 10Slide list1 = ['When', 'all', 'else'] list2 = ['fails,', 'read'] list1 = list1 + list2 + ['the', 'directions'] print(list1) my_list = [5, 2, 7] my_list = my_list + [3, 5] my_list = my_list + [6] print(my_list) list1 = ['When', 'all', 'else'] list2 = ['fails,', 'read'] list1 = list1 + list2 + ['the', 'directions'] print(list1) my_list = [5, 2, 7] my_list = my_list + [3, 5] my_list = my_list + [6] print(my_list) ['When', 'all', 'else', 'fails,', 'read', 'the', 'directions'] [5, 2, 7, 3, 5, 6]

Populate a list using the range() function  The Python range() function defines a sequence of integer values within two boundaries (from lecture 13).  The range() function can be used to populate a list, e.g., 11Slide my_list1 = list(range(5)) print("1.", my_list1) my_list2 = list(range(10, 20, 3)) print("2.", my_list2) my_list3 = list(range(10, 4, -2)) + list(range(4, 10, 3)) print("3.", my_list3) my_list1 = list(range(5)) print("1.", my_list1) my_list2 = list(range(10, 20, 3)) print("2.", my_list2) my_list3 = list(range(10, 4, -2)) + list(range(4, 10, 3)) print("3.", my_list3) 1. [0, 1, 2, 3, 4] 2. [10, 13, 16, 19] 3. [10, 8, 6, 4, 7]

The Python 'in' operator  The Python 'in' operator can be used to test if an element is currently present in a list. True is returned if the element is in the list, False otherwise e.g., 12Slide def search_feedback(test_value, a_list): if test_value in a_list: print('It is there') elif test_value + 1 in a_list or test_value - 1 in a_list: print('Close!') else: print('Not even close!') def main(): my_list = list(range(1, 5)) to_look_for = -1 search_feedback(to_look_for, my_list) search_feedback(5, my_list) main() def search_feedback(test_value, a_list): if test_value in a_list: print('It is there') elif test_value + 1 in a_list or test_value - 1 in a_list: print('Close!') else: print('Not even close!') def main(): my_list = list(range(1, 5)) to_look_for = -1 search_feedback(to_look_for, my_list) search_feedback(5, my_list) main() Not even close! Close!

Accessing elements of a list  Each element in a list can be accessed using its index number. (Remember: square brackets are used with lists.)  Note that accessing an element at an index value which doesn't exist in the list gives an index error: 13Slide def main(): a_list = ['What', 'I', "didn't", 'expect,', 'changed', 'me'] phrase = a_list[1] + " " + a_list[4] print(phrase) phrase = a_list[0] + " " + a_list[4] + " " + a_list[5] print(phrase) main() def main(): a_list = ['What', 'I', "didn't", 'expect,', 'changed', 'me'] phrase = a_list[1] + " " + a_list[4] print(phrase) phrase = a_list[0] + " " + a_list[4] + " " + a_list[5] print(phrase) main() I changed What changed me a_list = ['What', 'I', "didn't", 'expect,', 'changed', 'me'] print(a_list[6]) a_list = ['What', 'I', "didn't", 'expect,', 'changed', 'me'] print(a_list[6]) IndexError: list index out of range

Assigning new values to elements of the list  Elements of a list can be assigned new values. (Remember: square brackets are used with lists.) 14Slide def main(): my_list = [15, 12, 17, 10, 13, 18] print("1.", my_list) my_list[5] = my_list[5] + my_list[4] my_list[0] = my_list[1] + my_list[2] my_list[1] = my_list[1] * my_list[3] - 40 length = len(my_list) my_list[length - 2] = my_list[length - 1] print("2.", my_list) my_list[length - 1] = "Bye" print("3.", my_list) main() def main(): my_list = [15, 12, 17, 10, 13, 18] print("1.", my_list) my_list[5] = my_list[5] + my_list[4] my_list[0] = my_list[1] + my_list[2] my_list[1] = my_list[1] * my_list[3] - 40 length = len(my_list) my_list[length - 2] = my_list[length - 1] print("2.", my_list) my_list[length - 1] = "Bye" print("3.", my_list) main() 1. [15, 12, 17, 10, 13, 18] 2. [29, 80, 17, 10, 31, 31] 3. [29, 80, 17, 10, 31, 'Bye']

Give the output 15Slide def main(): nums1 = list(range(6)) nums2 = list(range(9, 6, -1)) nums1[0] = nums1[2] nums1[1] = nums1[4] + 2 nums1[2] = nums1[3] * nums2[0] nums1[1] = nums1[1] * nums1[1] nums2[1] = nums1[1] + 3 nums2 = nums2 + [nums1[4]] print(nums1) print(nums2) main() def main(): nums1 = list(range(6)) nums2 = list(range(9, 6, -1)) nums1[0] = nums1[2] nums1[1] = nums1[4] + 2 nums1[2] = nums1[3] * nums2[0] nums1[1] = nums1[1] * nums1[1] nums2[1] = nums1[1] + 3 nums2 = nums2 + [nums1[4]] print(nums1) print(nums2) main()

Visiting each element in the list  One way of accessing each element is shown below where each element is printed:  This is not a useful way of visiting each element. What if there were elements in the list? 16Slide def main(): my_list = ['We', 'are', 'not', 'anticipating', 'any', 'emergencies'] print(my_list[0]) print(my_list[1]) print(my_list[2]) print(my_list[3]) print(my_list[4]) print(my_list[5]) main() def main(): my_list = ['We', 'are', 'not', 'anticipating', 'any', 'emergencies'] print(my_list[0]) print(my_list[1]) print(my_list[2]) print(my_list[3]) print(my_list[4]) print(my_list[5]) main() We are not anticipating any emergencies

Visiting each element in the list  The for…in statement can be used to iterate through each element in the list structure (in their index order from 0 to the end of the list). 17Slide def main(): my_list = ['No', 'keyboard', 'detected.', 'Press', 'F1', 'to', 'continue'] for element in my_list: print(element) main() def main(): my_list = ['No', 'keyboard', 'detected.', 'Press', 'F1', 'to', 'continue'] for element in my_list: print(element) main() No keyboard detected. Press F1 to continue for item in my_list: print(item) for item in my_list: print(item) for word in my_list: print(word) for word in my_list: print(word)

List example  The following program processes each element of a list. 18Slide def count_items(a_list, max_allowed): count = 0 for item in a_list: if item < max_allowed: count += 1 return count def main(): my_list = list() for i in range(500): num = random.randrange(1, 500) my_list = my_list + [num] print(count_items(my_list, 250), "elements are under 250") main() def count_items(a_list, max_allowed): count = 0 for item in a_list: if item < max_allowed: count += 1 return count def main(): my_list = list() for i in range(500): num = random.randrange(1, 500) my_list = my_list + [num] print(count_items(my_list, 250), "elements are under 250") main() 238 elements are under 250

Complete the function  Complete the following function which is passed a list of numbers as a parameter and returns a new list in which each element is the squared value of the element in the original list. 19Slide def get_list_of_squares(a_list): def main(): my_list = list() for i in range(10): my_list = my_list + [random.randrange(1, 10)] print("1.", my_list) print("2.", get_list_of_squares(my_list)) main() def get_list_of_squares(a_list): def main(): my_list = list() for i in range(10): my_list = my_list + [random.randrange(1, 10)] print("1.", my_list) print("2.", get_list_of_squares(my_list)) main() 1. [8, 8, 3, 6, 9, 8, 6, 8, 2, 1] 2. [64, 64, 9, 36, 81, 64, 36, 64, 4, 1]

Complete the function  Complete the following function which is passed a list of numbers as a parameter. The function prints the largest and the smallest value in the list. You can assume that there is at least one element in the parameter list. 20Slide def print_min_max(a_list): def main(): my_list = list() for i in range(0, 20): my_list = my_list + [random.randrange(1, 20)] print(my_list) print_min_max(my_list) main() def print_min_max(a_list): def main(): my_list = list() for i in range(0, 20): my_list = my_list + [random.randrange(1, 20)] print(my_list) print_min_max(my_list) main() [14, 10, 10, 18, 9, 16, 12, 15, 7, 6, 7, 15, 17, 7, 19, 17, 6, 4, 9, 16] Largest: 19, Smallest: 4

Complete the function  Complete the print_xs() function which prints a line of characters. An "X" is printed if the corresponding element of the parameter list is True, otherwise a space is printed (see the output of the example below where the elements in position 0, 3 and 5 are True). 21Slide def print_xs(a_list): def main(): print(" ") my_list = [True, False, False, True, False, True] print_xs(my_list) main() def print_xs(a_list): def main(): print(" ") my_list = [True, False, False, True, False, True] print_xs(my_list) main() X X X

Summary  In a Python program:  a list object can be created  the length of a list can be obtained using the len() functions  the + operator is used to concatenate lists  the in operator is used to check if an element is in the list  we can iterate through the elements of a list using a for…in loop  calculations can done on the elements of a list 22Slide

Examples of Python features used in this lecture def print_section(): a_list = ['What', 'I', "didn't", 'expect,', 'changed', 'me'] phrase = a_list[1], a_list[4] print(phrase) phrase = a_list[0], a_list[4], a_list[5] print(phrase) def get_list_of_squares(a_list): count = 0 square_list = [] for item in a_list: square_list += [item * item] return square_list def create_list_of_randoms(): my_list = list() for i in range(500): num = random.randrange(1, 500) my_list += [num] 23Slide