Lecture 19 - More on Lists, Slicing Lists, List Functions COMPSCI 101 Principles of Programming.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Lists Introduction to Computing Science and Programming I.
2/28/2008. >>> Overview Arrays in Python – a.k.a. Lists Ranges are Lists Strings vs. Lists Tuples vs. Lists Map-Reduce Lambda Review: Printing to a file.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Guide to Programming with Python
Lists in Python.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
Lecture 20 – Test revision COMPSCI 101 Principles of Programming.
Lecture 21 - Tuples COMPSCI 101 Principles of Programming.
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
Chapter 7 Lists and Tuples. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. Data Structures.
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.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 8 Working.
10. Python - Lists The list is a most versatile datatype available in Python, which can be written as a list of comma-separated values (items) between.
Lists. The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Lists CS303E: Elements of Computers and Programming.
1 CSC 221: Introduction to Programming Fall 2011 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Lecture 15 – more on lists and for…in loops, the split() function COMPSCI 1 1 Principles of Programming.
Lists COMPSCI 105 S Principles of Computer Science.
1 CSC 221: Introduction to Programming Fall 2012 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
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.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
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.
Python Strings. String  A String is a sequence of characters  Access characters one at a time with a bracket operator and an offset index >>> fruit.
Lecture 14 – lists, for in loops to iterate through the elements of a list COMPSCI 1 1 Principles of Programming.
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.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
String and Lists Dr. José M. Reyes Álamo.
Topic: Python Lists – Part 1
COMPSCI 107 Computer Science Fundamentals
CS 100: Roadmap to Computing
CMPT 120 Topic: Python strings.
Chapter 10 Lists.
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Lists Part 1 Taken from notes by Dr. Neil Moore
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Bryan Burlingame 03 October 2018
Bryan Burlingame Halloween 2018
Ruth Anderson University of Washington CSE 160 Spring 2018
Chapter 10 Lists.
8 – Lists and tuples John R. Woodward.
4. sequence data type Rocky K. C. Chang 16 September 2018
Intro to Computer Science CS1510 Dr. Sarah Diesburg
String and Lists Dr. José M. Reyes Álamo.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Topics Sequences Introduction to Lists List Slicing
Lists Part 1 Taken from notes by Dr. Neil Moore
Basic String Operations
15-110: Principles of Computing
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Topics Sequences Lists Copying Lists Processing Lists
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Topics Basic String Operations String Slicing
Introduction to Computer Science
Bryan Burlingame Halloween 2018
Topics Sequences Introduction to Lists List Slicing
Topics Basic String Operations String Slicing
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CMPT 120 Topic: Python strings.
Topics Basic String Operations String Slicing
Introduction to Computer Science
Presentation transcript:

Lecture 19 - More on Lists, Slicing Lists, List Functions COMPSCI 101 Principles of Programming

 At the end of this lecture, students should be able to:  Understand various operators on lists  Understand various list functions  Understand mutability Learning outcomes CompSci Principles of Programming2

Accessing list elements  Specific elements in a list can be manipulated using square bracket notation and the index number of the element to be accessed. my_list = [10, 20, 30, 40, 50] print(my_list[2]) my_list[3] = my_list[1] + my_list[len(my_list) – 1] print(my_list[0], my_list[3]) my_list = [10, 20, 30, 40, 50] print(my_list[2]) my_list[3] = my_list[1] + my_list[len(my_list) – 1] print(my_list[0], my_list[3]) my_list CompSci Principles of Programming3

Accessing list elements  The elements of a list can be accessed from the end of the list backwards by using a negative index value. my_list = [10, 20, 30, 40, 50] print(my_list[-4]) my_list[-3] = my_list[-1] + my_list[–2] print(my_list[-3], my_list[2], my_list[-5]) my_list = [10, 20, 30, 40, 50] print(my_list[-4]) my_list[-3] = my_list[-1] + my_list[–2] print(my_list[-3], my_list[2], my_list[-5]) , 10 my_list This way, writing 'len(my_list) - …' to access elements from the end of the lists can be avoided CompSci Principles of Programming4

Index out of Range - IndexError  Warning! If you try to access an element that does not exist, Python will throw an error! my_list = [10, 20, 30, 40, 50] print(my_list[5]) print(my_list[-6]) my_list = [10, 20, 30, 40, 50] print(my_list[5]) print(my_list[-6]) IndexError: list index out of range my_list #NO! Element at index 5 does not exist #NO! Element at index -6 does not exist CompSci Principles of Programming5

The 'in' Operator (membership)  The in operator returns a boolean. It returns True if the value (on the left hand side of the in operator) is present in the list. Otherwise the in operator returns False. my_list = [10, 20, 30, 40, 50] result1 = 100 in my_list print(result1) print(30 in my_list) print(40 not in my_list) my_list = [10, 20, 30, 40, 50] result1 = 100 in my_list print(result1) print(30 in my_list) print(40 not in my_list) False True False CompSci Principles of Programming6

Visiting each element in a list (iteration)  We can iterate through all the elements of a list, in order, using a for … in loop, e.g., my_list = [10, 20, 30, 40, 50] total = 0 for element in my_list: if element % 4 == 0: total = total + element print(total) my_list = [10, 20, 30, 40, 50] total = 0 for element in my_list: if element % 4 == 0: total = total + element print(total) 60 CompSci Principles of Programming7

The + Operator (concatenation)  Applying the + operator to two lists produces a new list containing all the elements of the first list followed by all the elements of the second list. list1 = [10, 20, 30, 40, 50] list2 = [100, 200] list3 = list1 + list2 print("1.", list3) print("2.", 100 in list1) print("3.", 40 not in list2) list3 = list3 + [-4] print("4.", list3) list1 = [10, 20, 30, 40, 50] list2 = [100, 200] list3 = list1 + list2 print("1.", list3) print("2.", 100 in list1) print("3.", 40 not in list2) list3 = list3 + [-4] print("4.", list3) 1. [10, 20, 30, 40, 50, 100, 200] 2. False 3. True 4. [10, 20, 30, 40, 50, 100, 200, -4] You can only concatenate two lists (not a list and a string, not a list and an integer, etc.). CompSci Principles of Programming8

The * Operator (repeat)  The * operator produces a new list which "repeats" the original list's contents. list1 = [10, 20] list2 = list1 * 2 list3 = list2 * 3 print("1.", list1) print("2.", list2) print("3.", list3) list1 = [10, 20] list2 = list1 * 2 list3 = list2 * 3 print("1.", list1) print("2.", list2) print("3.", list3) 1. [10, 20] 2. [10, 20, 10, 20] 3. [10, 20, 10, 20, 10, 20, 10, 20, 10, 20, 10, 20] You can replicate a list only in combination with an integer, i.e., * an_integer. CompSci Principles of Programming9

Getting slices of lists  The slice operation behaves the same way as it does with the elements of a string. Within square brackets, you may have one or two colons (:). The number before the first colon is the start index, the number after the first colon is the end index, and the number after the second colon is the step.  The step indicates the gap between elements in the slice taken. The default step is 1. list1 = [10, 20, 30, 40, 50] list2 = list1[0:3 :1 ] print("1.", list2) list3 = list1[3:5 :1 ] print("2.", list3) list1 = [10, 20, 30, 40, 50] list2 = list1[0:3 :1 ] print("1.", list2) list3 = list1[3:5 :1 ] print("2.", list3) list1 = [10, 20, 30, 40, 50] list2 = list1[0:3] print("1.", list2) list3 = list1[3:5] print("2.", list3) list1 = [10, 20, 30, 40, 50] list2 = list1[0:3] print("1.", list2) list3 = list1[3:5] print("2.", list3) Does the same job as 1. [10, 20, 30] 2. [40, 50] CompSci Principles of Programming10

Getting slices of lists  The number before the first colon is the start index, the number after the first colon is the end index, and the number after the second colon is the step. list1 = [10, 20, 30, 40, 50, 60] list2 = list1[ 0:5:3 ] print("1.", list2) list3 = list1[ 2:5:2 ] print("2.", list3) list1 = [10, 20, 30, 40, 50, 60] list2 = list1[ 0:5:3 ] print("1.", list2) list3 = list1[ 2:5:2 ] print("2.", list3) 1. [10, 40] 2. [30, 50] CompSci Principles of Programming11

Getting slices of lists  The number after the second colon is the step. The step can be a negative number. The default step is 1 (see previous slide). 1. [] 2. [55, 40] 3. [55, 40, 20] list1 = [10, 20, 30, 40, 50, 55] list2 = list1[1:6: -3 ] print("1.", list2) list3 = list1[-1:-4: -2 ] print("2.", list3) list4 = list1[-1:-6: -2 ] print("3.", list4) list1 = [10, 20, 30, 40, 50, 55] list2 = list1[1:6: -3 ] print("1.", list2) list3 = list1[-1:-4: -2 ] print("2.", list3) list4 = list1[-1:-6: -2 ] print("3.", list4) list CompSci Principles of Programming12

Getting slices of lists  Three numbers in square brackets separated by colons define the start, end and step of the slice, e.g., list1[1:6:3].  The default for the first number is the beginning of the list, e.g.,  The default for the second number is the end of the list, e.g., list1 = [10, 20, 30, 40, 50, 55] list2 = list1[:4:1] #same as list2 = list1[0:4:1] print(list2) list1 = [10, 20, 30, 40, 50, 55] list2 = list1[:4:1] #same as list2 = list1[0:4:1] print(list2) [10, 20, 30, 40] list1 = [10, 20, 30, 40, 50, 55] list2 = list1[2::2] #same as list2 = list1[2:len(list1):2] print(list2) list1 = [10, 20, 30, 40, 50, 55] list2 = list1[2::2] #same as list2 = list1[2:len(list1):2] print(list2) [30, 50] CompSci Principles of Programming13

The is operator  The == operator is used to test if two objects contain the same information.  The is operator is used to test if two variables reference (point to) the same object. word1 = "sweet" word2 = word1 print("1.", word1 == word2) print("2.", word1 is word2) word2 = word2.upper() word2 = word2.lower() print("3.", word1 == word2) print("4.", word1 is word2) word1 = "sweet" word2 = word1 print("1.", word1 == word2) print("2.", word1 is word2) word2 = word2.upper() word2 = word2.lower() print("3.", word1 == word2) print("4.", word1 is word2) 1. True 2. True 3. True 4. False CompSci Principles of Programming14

Strings are immutable  Strings are "immutable", i.e., the characters in a string object cannot be changed. Whenever a string is changed in some way, a new string object is created. word1 = "sweet" word2 = word1 print("1.", word1, word2) print("2.", word1 is word2) word2 = word2 + " dumpling" print("3.", word1, word2) print("4.", word1 is word2) word1 = "sweet" word2 = word1 print("1.", word1, word2) print("2.", word1 is word2) word2 = word2 + " dumpling" print("3.", word1, word2) print("4.", word1 is word2) 1. sweet sweet 2. True 3. sweet sweet dumpling 4. False CompSci Principles of Programming15

Lists are Mutable  Lists are "mutable", i.e., the contents of a list object can be changed. list1 = [10, 20, 30, 40, 50] list2 = [1, 5] #A print("1.", list1) print("2.", list2) print("3.", list1 is list2) list2 = list1 #B print("4.", list1 is list2) list1[3] = 99 list2[1] = 3 #C print("5.", list1) print("6.", list2) print("7.", list1 is list2) list1 = [10, 20, 30, 40, 50] list2 = [1, 5] #A print("1.", list1) print("2.", list2) print("3.", list1 is list2) list2 = list1 #B print("4.", list1 is list2) list1[3] = 99 list2[1] = 3 #C print("5.", list1) print("6.", list2) print("7.", list1 is list2) 1. [10, 20, 30, 40, 50] 2. [1, 5] 3. False 4. True 5. [10, 3, 30, 99, 50] 6. [10, 3, 30, 99, 50] 7. True A B C CompSci Principles of Programming16

Some functions that work with lists  Below are four in-built functions which can be used with lists:  len(a_list) returns the number of elements.  min(a_list) returns the minimum element in the list.  max(a_list) returns the maximum element in the list.  sum(a_list) returns the sum of the elements in the list (only for numbers). list1 = [10, 20, 30, 40, 50, 55] minimum = min(list1) sum = sum(list1) print("length:", len(list1), "min:", minimum, "max:", max(list1), "sum:", total) list1 = [10, 20, 30, 40, 50, 55] minimum = min(list1) sum = sum(list1) print("length:", len(list1), "min:", minimum, "max:", max(list1), "sum:", total) length: 6 min: 10 max: 55 sum: 205 CompSci Principles of Programming17

Dot notation  We use dot notation to call a function on a specific object. In dot notation, a dot is placed between the object and the function which is being applied to the object.  Each type of object has many functions which can be called using that object. For example a string object can use find(), upper(), lower(), strip(), isdigit(), isalpha(), …. words = "Over the rainbow" position = words.find("r") words = words.lower() result = words.isalpha() print("position:", position, "result:", result,"words:", words) words = "Over the rainbow" position = words.find("r") words = words.lower() result = words.isalpha() print("position:", position, "result:", result,"words:", words) position: 3 result: False words: over the rainbow CompSci Principles of Programming18

Some list functions  There are many functions which can be used with a list object. Below and on the next slides are five function which can be used with lists:  index(x) returns the index of the first element from the left in the list with a value equal to x. Python throws an error if there is no such value in the list. Because of this, index(x) is usually preceded by a check for that element using the in operator. list1 = [10, 20, 30, 40, 50, 55] if 40 in list1:#check first position = list1.index(40) print("40 is in position", position, "in the list") else: print("40 is not in the list") list1 = [10, 20, 30, 40, 50, 55] if 40 in list1:#check first position = list1.index(40) print("40 is in position", position, "in the list") else: print("40 is not in the list") 40 is in position 3 in the list CompSci Principles of Programming19

Some list functions  pop(index) removes and returns the item at the position given by the index number. An error results if there is no such index in the list. pop() with no index removes and returns the last item. list1 = [10, 20, 30, 40, 50, 55] if len(list1) > 2: popped = list1.pop(2) print("Popped item", popped, " from the list", list1) print(list1.pop()) list1 = [10, 20, 30, 40, 50, 55] if len(list1) > 2: popped = list1.pop(2) print("Popped item", popped, " from the list", list1) print(list1.pop()) Popped item 30 from the list [10, 20, 40, 50, 55] 55 CompSci Principles of Programming20

Another list function  insert(i, x) inserts an element at a given position. The first argument is the index at which to insert the element, e.g., my list.insert(1, 62) inserts 62 into position 1 of the list, moving the rest of the elements up one (the element at index 1 moves to index 2, the element at index 2 moves to index 3, and so on). list1 = [10, 20, 30, 40, 50, 55] list1.insert(3, 77) print(list1) list1.insert(6, 99) print(list1) list1.insert(0, 44) print(list1) list1 = [10, 20, 30, 40, 50, 55] list1.insert(3, 77) print(list1) list1.insert(6, 99) print(list1) list1.insert(0, 44) print(list1) [10, 20, 30, 77, 40, 50, 55] [10, 20, 30, 77, 40, 50, 99, 55] [44, 10, 20, 30, 77, 40, 50, 99, 55] CompSci Principles of Programming21

Another list function  append(x) adds the element to the end of the list. list1 = [10, 20, 30, 40, 50, 55] list1.append(77) print("1.", list1) list1.append(99) print("2.", list1) list1.append(44) print("3.", list1) list1 = [10, 20, 30, 40, 50, 55] list1.append(77) print("1.", list1) list1.append(99) print("2.", list1) list1.append(44) print("3.", list1) 1. [10, 20, 30, 40, 50, 55, 77] 2. [10, 20, 30, 40, 50, 55, 77, 99] 3. [10, 20, 30, 40, 50, 55, 77, 99, 44] CompSci Principles of Programming22

More useful list functions  sort() sorts the elements of the list, in place. If sorting a list of lists, only the first element in each list is considered in the comparison operations. Only the order of the list elements is modified (unless already sorted).  reverse() reverses the elements of the list, in place. Only the order of the list elements is modified. list1 = [10, 20, 30, 40, 50, 55] print(list1) list1.reverse() print(list1) list1 = [10, 20, 30, 40, 50, 55] print(list1) list1.reverse() print(list1) [10, 20, 30, 40, 50, 55] [55, 50, 40, 30, 20, 10] list1 = [60, 20, 80, 10, 30, 55] print(list1) list1.sort() print(list1) list1 = [60, 20, 80, 10, 30, 55] print(list1) list1.sort() print(list1) [60, 20, 80, 10, 30, 55] [10, 20, 30, 55, 60, 80] CompSci Principles of Programming23

Summary  A list stores data as a sequence  We use a for … in … to iterate through the contents of a list  len() returns the number of elements in a list  min() returns the minimum of the elements in a list  max() returns the maximum of the elements in a list  sum() returns the sum of the elements in a list  Each element of the list can be accessed using the index operator. The index can be negative (starting from the end of the list)  Slices of lists can be obtained by using [slice_start:slice_end:step]  index(element) returns the index of the element in a list  insert(position, element) inserts an element into a list into the required position  append(element) adds the element to the end of the list  reverse() reverses the elements of a list in place  sort() sorts the elements of a list in place  Lists are mutable CompSci Principles of Programming24

Examples of Python features used in this lecture list1 = [4, 6, 2, 5, 8] result = 8 in list1 for element in list1: … min_value = len(list1) min_value = min(list1) max_value = max(list1) #if the list elements are numbers total = sum(list1) #if the list elements are numbers element_from_end = list1[-2] list2 = list1[1:5:2] position = list1.index(3) element = list1.pop(1) list1.insert(4, 66) list1.append(54) list1.reverse() list1.sort() CompSci Principles of Programming25