Fundamentals of Python: First Programs PDF

Summary

This document is about lists and dictionaries in Python programming. It provides examples of how to create and manipulate lists and dictionaries. Objectives for the chapter are also covered.

Full Transcript

Fundamentals of Python: First Programs Second Edition Chapter 5 Lists and Dictionaries © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, excep...

Fundamentals of Python: First Programs Second Edition Chapter 5 Lists and Dictionaries © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 1 Objectives (1 of 2) 5.1 Construct lists and access items in those lists 5.2 Use methods to manipulate lists 5.3 Perform traversals of lists to process items in the lists 5.4 Define simple functions that expect parameters and return values © 2018 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. Objectives (2 of 2) 5.5 Construct dictionaries and access entries in those dictionaries 5.6 Use methods to manipulate dictionaries 5.7 Determine whether a list or a dictionary is an appropriate data structure for a given application © 2018 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. Introduction A list allows the programmer to manipulate a sequence of data values of any types A dictionary organizes data values by association with other data values rather than by sequential position Lists and dictionaries provide powerful ways to organize data in useful and interesting applications © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 4 Lists List: Sequence of data values (items or elements) Some examples: Shopping list for the grocery store To-do list Roster for an athletic team Guest list for a wedding Recipe, which is a list of instructions Text document, which is a list of lines Names in a phone book Each item in a list has a unique index that specifies its position (from 0 to length – 1) © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 5 List Literals and Basic Operators (1 of 4) Some examples: [‘apples’, ‘oranges’, ‘cherries’] [[5, 9], [541, 78]] When an element is an expression, its value is included in the list: >>> import math >>> x = 2 >>> [x, math.sqrt(x)] [2, 1.4142135623730951] >>> [x + 1] © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 6 List Literals and Basic Operators (2 of 4) Lists of integers can be built using range: >>> first = [1, 2, 3, 4] >>> second = list(range(1, 5)) >>> first [1, 2, 3, 4] >>> second [1, 2, 3, 4] The list function can build a list from any iterable sequence of elements: >>> third = list(“Hi there!”) >>> third [‘H’, ‘I’, ‘ ’ , ‘t’, ‘h’, ‘e’, ‘r’, ‘e’, ‘!’] © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 7 List Literals and Basic Operators (3 of 4) len, [], +, and == work on lists as expected: >>> len(first) 4 >>> first 1 >>> first[2:4] [3, 4] Concatenation (+) and equality (==) also work as expected for lists: >>> first + [5, 6] [1, 2, 3, 4, 5, 6] >>> first == second True © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 8 List Literals and Basic Operators (4 of 4) To print the contents of a list: >>> print(“1234”) 1234 >>> print([1, 2, 3, 4]) [1, 2, 3, 4] in detects the presence of an element: >>> 3 in [1, 2, 3] True >>> 0 in [1, 2, 3] False © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 9 Replacing an Element in a List (1 of 2) A list is mutable Elements can be inserted, removed, or replaced The list itself maintains its identity, but its state—its length and its contents—can change Subscript operator is used to replace an element: >>> example = [1, 2, 3, 4] >>> example [1, 2, 3, 4] >>> example = 0 >>> example [1, 2, 3, 0] Subscript is used to reference the target of the assignment, which is not the list but an element’s position within it © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 10 Replacing an Element in a List (2 of 2) The first session shows how to replace each number in a list with >>> its square: numbers = [2, 3, 4, 5] >>> numbers [2, 3, 4, 5] >>> for index in range(len(numbers)): numbers[index] = numbers[index] ** 2 >>> numbers [4, 9, 16, 25] Next session uses the string method split to extract a list of words: >>> sentence = “This example has five words. ” >>> words = sentence.split() >>> words [‘This’, ‘example’, ‘has’, ‘five’, ‘words.’] >>> for index in range(len(words)): words[index] = words[index].upper() >>> words [‘THIS’, ‘EXAMPLE’, ‘HAS’, ‘FIVE’, ‘WORDS.’] © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 11 List Methods for Inserting and Removing Elements (1 of 4) The list type includes several methods for inserting and removing elements List Method What It Does L..append(element) Adds element to the end of L L.extend(aList) Adds the elements of aList to the end of L L..insert(index, element) Inserts element at index if index is less than the length of L. Otherwise, inserts element at the end of L. L.pop() Removes and returns the element at the end of L. L.pop(index) Removes and returns the element at index © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 12 List Methods for Inserting and Removing Elements (2 of 4) The method insert expects an integer index and the new element as arguments >>> example = [1, 2] >>> example [1, 2] >>> example.insert(1, 10) >>> example [1, 10, 2] >>> example.insert(3, 25) >>> example [1, 10, 2, 25] © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 13 List Methods for Inserting and Removing Elements (3 of 4) The method append expects just the new element as an argument and adds the new element to the end of the list The method extend performs a similar operation, but adds the elements of its list argument to the end of the list >>> example = [1, 2] >>> example [1, 2] >>> example.append(3) >>> example [1, 2, 3] >>> example.extend([11, 12, 13]) >>> example [1, 2, 3, 11, 12, 13] >>> example + [14, 15] [1, 2, 3, 11, 12, 13, 14, 15] >>> example [1, 2, 3, 11, 12, 13] © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 14 List Methods for Inserting and Removing Elements (4 of 4) The method pop is used to remove an element at a given position >>> example [1, 2, 10, 11, 12, 13] >>> example.pop() # Remove the last element 13 >>> example [1, 2, 10, 11, 12] >>> example.pop(0) # Remove the first element 1 >>> example [2, 10, 11, 12] © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 15 Searching a List in determines an element’s presence or absence, but does not return position of element (if found) Use method index to locate an element’s position in a list Raises an error when the target element is not found aList = [34, 45, 67] target = 45 if target in aList: print(aList.index(target)) else: print(−l) © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 16 Sorting a List A list’s elements are always ordered by position, but you can impose a natural ordering on them For example, in alphabetical order When the elements can be related by comparing them , and ==, they can be sorted The method sort mutates a list by arranging its elements in ascending >>> order example = [4, 2, 10, 8] >>> example [4, 2, 10, 8] >>> example.sort() >>> example [2, 4, 8, 10] © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 17 Mutator Methods and the Value None All of the functions and methods examined in previous chapters return a value that the caller can then use to complete its work Mutator methods (e.g., insert, append,extend,pop,and sort) usually return no value of interest to caller Python automatically returns the special value None >>> aList = aList.sort() >>> print(aList) None © 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for classroom use. 18

Use Quizgecko on...
Browser
Browser