Topics Sequences Lists Copying Lists Processing Lists

Slides:



Advertisements
Similar presentations
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Advertisements

Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
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.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
REPETITION STRUCTURES. Topics Introduction to Repetition Structures The while Loop: a Condition- Controlled Loop The for Loop: a Count-Controlled Loop.
Lists in Python.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
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.
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.
Lecture 19 - More on Lists, Slicing Lists, List Functions COMPSCI 101 Principles of Programming.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Lists CS303E: Elements of Computers and Programming.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
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 Programing: An Introduction to Computer Science
INLS 560 – S TRINGS Instructor: Jason Carter. T YPES int list string.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
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.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
String and Lists Dr. José M. Reyes Álamo.
Topic: Python Lists – Part 1
COMPSCI 107 Computer Science Fundamentals
Containers and Lists CIS 40 – Introduction to Programming in Python
Topics Introduction to Repetition Structures
JavaScript: Functions.
Topics Introduction to Repetition Structures
Introduction to Python
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Introduction to Python
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Bryan Burlingame Halloween 2018
Guide to Programming with Python
Chapter 3: Introduction to Problem Solving and Control Statements
CS190/295 Programming in Python for Life Sciences: Lecture 6
8 – Lists and tuples John R. Woodward.
4. sequence data type Rocky K. C. Chang 16 September 2018
Object Oriented Programming in java
CS 1111 Introduction to Programming Fall 2018
ERRORS AND EXCEPTIONS Errors:
String and Lists Dr. José M. Reyes Álamo.
Topics Introduction to Repetition Structures
Reading Input from the Keyboard
Starting Out with Programming Logic & Design
Topics Sequences Introduction to Lists List Slicing
Basic String Operations
Using the Target Variable Inside the Loop
CS 1111 Introduction to Programming Spring 2019
15-110: Principles of Computing
Topics Basic String Operations String Slicing
Topics Introduction to Repetition Structures
Bryan Burlingame Halloween 2018
Topics Sequences Introduction to Lists List Slicing
And now for something completely different . . .
Topics Basic String Operations String Slicing
Exception Handling COSC 1323.
Topics Introduction to File Input and Output
Topics Basic String Operations String Slicing
Introduction to Computer Science
Selamat Datang di “Programming Essentials in Python”
Presentation transcript:

Topics Sequences Lists Copying Lists Processing Lists Two-Dimensional Lists

Sequences An object that contains multiple items of data The items are stored in sequence one after another You can examine and manipulate items stored in it Python provides different types of sequences, including lists and tuples Both can hold various types of data The difference between these is that a list is mutable and a tuple is immutable Where a program can change the contents

Introduction to Lists An object that contains multiple data items Items can be added and removed Can use indexing, slicing, etc. to work with lists Each item is an element Has more capabilities than arrays in other languages Format: list = [item1, item2, etc.] Example: even_numbers = [2, 4, 6, 8, 10] Can hold items of different types Info = [‘Alicia’, 27, 1550.87]

Introduction to Lists

Displaying Lists print function can be used to display an entire list Numbers = [5, 10, 15, 20] Print (numbers) Output: [5, 10, 15, 20]

list() Function list() function can convert certain types of objects to lists like the range function does Example 1: Numbers = list(range(5)) Print(Numbers) Output: [0, 1, 2, 3, 4] Example 2: Numbers = list(range(1, 10, 2)) Print (Numbers) Output [1, 3, 5, 7, 9]

The Repetition Operator and Iterating over a List Repetition operator: makes multiple copies of a list and joins them together The * symbol is a repetition operator when applied to a sequence and an integer Sequence is left operand, how many times to replicate on right General format: list * n Example: Numbers = [0] * 5 Produces [0, 0, 0, 0, 0] Numbers = [1, 2, 3] * 3 Produces [1, 2, 3, 1, 2, 3, 1, 2, 3]

Iterating Over a List You can iterate over a list using a for loop Format: for x in list: Example: Numbers = [ 99, 100, 101, 102] For n in numbers: print(n) Output: 99 100 101 102

Indexing Index: a number specifying the position of an element in a list Enables access to individual element in list Index of first element in the list is 0, second element is 1, and n’th element is n-1 Negative indexes identify positions relative to the end of the list The index -1 identifies the last element, -2 identifies the next to last element, etc.

Indexing Examples Output: 10 20 30 40 10 20 30 40 my_list = [10, 20, 30, 40] print (my_list[0], my_list[1], my_list[2], my_list[3]]) Output: 10 20 30 40 for i in range(4): print(my_list[i]) 10 20 30 40

Negative Indexing Output: 40 30 20 10 my_list = [10, 20, 30, 40] print (my_list[-1], my_list[-2], my_list[-3], my_list[-4]]) Output: 40 30 20 10

The len function An IndexError exception is raised if an invalid index is used len function: returns the length of a sequence such as a list Example: size = len(my_list) Returns the number of elements in the list, so the index of last element is len(list)-1 Can be used to prevent an IndexError exception when iterating over a list with a loop

Lists Are Mutable Mutable sequence: the items in the sequence can be changed Lists are mutable, and so their elements can be changed An expression such as list[1] = new_value can be used to assign a new value to a list element Must use a valid index to prevent raising of an IndexError exception

Mutable Example Output: [99, 2, 3, 4] Numbers = [1, 2, 3, 4] Print (numbers) Numbers[0] = 99 Output: [1, 2, 3, 4] [99, 2, 3, 4] Another example can be seen in sales_list.py in book

Concatenating Lists Concatenate: join two things together The + operator can be used to concatenate two lists Cannot concatenate a list with another data type, such as a number The += augmented assignment operator can also be used to concatenate lists Example:

Concatenating Lists Example List = list1 + list2 Output: [1, 2, 3, 4, 5, 6, 7, 8]

List Slicing Slice: a range of items taken from a sequence List slicing format: list[start : end] Span is a list containing copies of elements from start up to, but not including, end If start not specified, 0 is used for start index Ex: numbers[:3] If end not specified, len() of list is used for end index numbers[2:] Slicing expressions can include a step value and negative indexes relative to end of list

List Slicing Example Output: [‘Tuesday’, ‘Wednesday’, ‘Thursday’ ] days = [‘Sunday’, ‘Monday’, ‘Tuesday’,\ ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’] mid_days = days[2:5] print (mid_days) Output: [‘Tuesday’, ‘Wednesday’, ‘Thursday’ ]

Finding Items in Lists with the in Operator You can use the in operator to determine whether an item is contained in a list General format: item in list Returns True if the item is in the list, or False if it is not in the list Similarly you can use the not in operator to determine whether an item is not in a list

Exceptions Exception: error that occurs while a program is running Usually causes program to abruptly halt Ex: user enters string when expecting integer Traceback: error message that gives information regarding line numbers that caused the exception Indicates the type of exception and brief description of the error that caused exception to be raised

Exceptions Many exceptions can be prevented by careful coding Example: input validation Some exceptions cannot be avoided by careful coding Examples Trying to convert non-numeric string to an integer

Exception Handler Code that responds when exceptions are raised Prevents program from crashing Python uses try/except statement General format: try: Statements except exceptionName: try suite: statements that can potentially raise an exception except block: event handler

Exceptions If statement in try suite raises exception: Use statements in except clause Handler immediately following except clause executes Continue program after try/except statement Other exceptions: Program halts with traceback error message If no exception is raised, handlers are skipped

Exceptions Example # This program calculates gross pay. try: # Get the number of hours worked. hours = int(input('How many hours did you work? ')) pay_rate = float(input('Enter your hourly pay rate: ')) gross_pay = hours * pay_rate # Display the gross pay. print('Gross pay: $', format(gross_pay, ',.2f'), sep='') except ValueError: print('ERROR: Hours worked and hourly pay rate must') print('be valid integers.')

In List Example # This program demonstrates the in operator used with a list. # Create a list of product numbers. prod_nums = ['V475', 'F987', 'Q143', 'R688'] # Get a product number to search for. search = input('Enter a product number: ') # Determine whether the product number is in the list. if search in prod_nums: print(search, 'was found in the list.') else: print(search, 'was not found in the list.') Output: Enter a product number: V475 V745 was found in the list. Enter a product number: v475 v745 was not found in the list.

List Methods and Useful Built-in Functions append(item): used to add items to a list – item is appended to the end of the existing list index(item): used to determine where an item is located in a list Returns the index of the first element in the list containing item Raises ValueError exception if item not in the list

List Append Example # This program demonstrates how the append # method can be used to add items to a list. # First, create an empty list. name_list = [ ] # Create an empty list again = 'Y‘ # Create a variable to control the loop. while again.upper() == 'Y': # Add some names to the list. name = input('Enter a name: ') # Get a name from the user. name_list.append(name) # Append the name to the list. print('Do you want to add another name?') again = input('y = yes, anything else = no: ') print() print('Here are the names you entered.') for name in name_list: print(name)

Index List Example # This program demonstrates how to get the index of an item in a list and # then replace that item with a new item. food = ['Pizza', 'Burgers', 'Chips'] print('Here are the items in the food list:') # Display the list. print(food) item = input('Which item should I change? ') # Get the item to change. try: item_index = food.index(item) # Get the item's index in the list new_item = input('Enter the new value: ') # Get value to replace it food[item_index] = new_item # Replace the old item with new item print('Here is the revised list:') except ValueError: print('That item was not found in the list.')

List Methods and Useful Built-in Functions insert(index, item): used to insert item at position index in the list sort(): used to sort the elements of the list in ascending order remove(item): removes the first occurrence of item in the list reverse(): reverses the order of the elements in the list

List Methods and Useful Built-in Functions del statement: removes an element from a specific index in a list General format: del list[i] min and max functions: built-in functions that returns the item that has the lowest or highest value in a sequence The sequence is passed as an argument

Copying Lists If you set one list equal to another list they will point to same place in memory When you make change to one list the other will also change To make a copy of a list you must copy each element of the list Two methods to do this: Creating a new empty list and using a for loop to add a copy of each element from the original list to the new list Creating a new empty list and concatenating the old list to the new empty list

Copying Lists

Two-Dimensional Lists A list that contains other lists as its elements Also known as nested list Common to think of two-dimensional lists as having rows and columns Useful for working with multiple sets of data To process data in a two-dimensional list need to use two indexes Typically use nested loops to process

Two-Dimensional Lists

Two-Dimensional Lists

Two-Dimensional List Example Students = [[‘Joe’, ‘Kim’], [‘Sam’, ‘Sue’], [‘Kelly’, ’Chris’]] Output: [[‘Joe’, ‘Kim’], [‘Sam’, ‘Sue’], [‘Kelly’, ’Chris’]] print(student[0]) [‘Joe’, ‘Kim’]