Presentation is loading. Please wait.

Presentation is loading. Please wait.

Topics Sequences Lists Copying Lists Processing Lists

Similar presentations


Presentation on theme: "Topics Sequences Lists Copying Lists Processing Lists"— Presentation transcript:

1

2 Topics Sequences Lists Copying Lists Processing Lists
Two-Dimensional Lists

3 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

4 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, ]

5 Introduction to Lists

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

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

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

9 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

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

11 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: for i in range(4): print(my_list[i]) 10 20 30 40

12 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:

13 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

14 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

15 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

16 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:

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

18 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

19 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’ ]

20 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

21 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

22 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

23 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

24 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

25 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.')

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

27 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

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

29 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.')

30 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

31

32 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

33 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

34 Copying Lists

35 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

36 Two-Dimensional Lists

37 Two-Dimensional Lists

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


Download ppt "Topics Sequences Lists Copying Lists Processing Lists"

Similar presentations


Ads by Google