Download presentation
Presentation is loading. Please wait.
Published byStewart Arron Chambers Modified over 9 years ago
1
CSCI/CMPE 4341 Topic: Programming in Python Chapter 6: Lists, Tuples, and Dictionaries Xiang Lian The University of Texas – Pan American Edinburg, TX 78539 lianx@utpa.edu 1
2
Objectives In this chapter, you will: – Understand Python sequences – Learn the list, tuple, and dictionary data types – Know how to create, initialize, and refer to individual elements of lists, tuples, and dictionaries – Explore how to use lists to sort and search sequences of values – Learn how to pass lists to functions – Become familiar with list and dictionary methods 2
3
Introduction Data structures – Structures that hold and organize information Sequences – Also known as arrays in other languages (e.g., C++) – Store related data types – 3 types Strings Lists Tuples Mappings – In most languages called hashes or associative arrays – Dictionaries are the only python mapping container Key-value pairs 3
4
Sequences – Series of items that are often related – Strings are sequences in Python – A sequence is returned by the range function 4
5
Example of Sequences C[0]-45C[-12] C[1]6C[-11] C[2]0C[-10] C[3]72C[-9] C[4]34C[-8] C[5]39C[-7] C[6]98C[-6] C[7]-1345C[-5] C[8]939C[-4] C[9]10C[-3] C[10]40C[-2] C[11]33C[-1] Name sequence (C) Position number of the element within sequence C 5
6
Sequences (cont'd) Elements – The individual items in each sequence Referred to by subscripts Obtain one by using sequenceName[ subscript ] – The subscript of the first element is 0 – The subscript of the last element can be -1 6
7
Creating Sequences – String Strings – Use quotes string1 = "hello" – Empty string string2 = "" 7
8
Creating Sequences – List Lists – Use brackets – Separate multiple items with a comma list1 = [1, 2, 3, 4] – Empty list list2 = [] Length of the list – len (list1) 8
9
Creating Sequences – Tuple Tuples – Use parenthesis – Separate multiple items with a comma tuple1 = (1, 2, 3, 4) tuple1 = 1, 2, 3, 4 – Empty tuple tuple2 = () – Singleton (or one-element tuple) singleton3 = 1, Comma (,) after 1 identify the variable signleton3 as a tuple 9
10
Differences Between Lists and Tuples Differences – Tuples and lists can both contain the same data aList = [ 1, 2, 3, 4 ] aTuple = ( 1, 2, 3, 4 ) – For practical purposes though each is used to hold different types of items 10
11
Lists Not restricted to values of the same type – Programmers use lists to hold data that is of the same type The length is usually not predetermined and can vary throughout the program Accessing elements out of range – Python exits and an out of range error is displayed 11
12
2002 Prentice Hall. All rights reserved. Outline Fig05_03.py # Fig. 5.3: fig05_03.py # Creating, accessing and changing a list. aList = [] # create empty list # add values to list for number in range( 1, 11 ): aList += [ number ] print ("The value of aList is:", aList) # access list values by iteration print ("\nAccessing values by iteration:") for item in aList: print (item, end=" ") print () # access list values by index print ("\nAccessing values by index:") print ("Subscript Value") for i in range( len( aList ) ): print ("%9d %7d" % ( i, aList[ i ] )) # modify list print ("\nModifying a list value...") print ("Value of aList before modification:", aList) aList[ 0 ] = -100 aList[ -3 ] = 19 print ("Value of aList after modification:", aList) Adds the values 1 to 10 to the list Prints the list, both all at once and one at a time Prints the list in comparison to its subscripts Sets the value of the first item to -100Sets the value of the 8 th item to 19 12
13
Syntax Error When Using Lists Python 3.4 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> aList = [ 1 ] >>> print (aList[ 13 ]) Traceback (most recent call last): File " ", line 1, in ? IndexError: list index out of range Fig. 5.4Out-of-range error. 13
14
2002 Prentice Hall. All rights reserved. Outline Fig05_05.py # Fig. 5.5: fig05_05.py # Creating a histogram from a list of values. values = [] # a list of values # input 10 values from user print ("Enter 10 integers:") for i in range( 10 ): newValue = int( input( "Enter integer %d: " % ( i + 1 ) ) ) values += [ newValue ] # create histogram print ("\nCreating a histogram from values:" ) print ("%s %10s %10s" % ( "Element", "Value", "Histogram" ) ) for i in range( len( values ) ): print ("%7d %10d %s" % ( i, values[ i ], "*" * values[ i ] )) Prompts the user for 10 integers Outputs as many * ’s as the number entered into the list by the user 14
15
Tuples Used to contain data that are related but not necessarily of the same type – Each data item represents a unique piece of the overall portion For example, a person’s name, age and birth date 15
16
2002 Prentice Hall. All rights reserved. Outline Fig05_06.py Program Output # Fig. 5.6: fig05_06.py # Creating and accessing tuples. # retrieve hour, minute and second from user hour = int( input( "Enter hour: " ) ) minute = int( input( "Enter minute: " ) ) second = int( input( "Enter second: " ) ) currentTime = hour, minute, second # create tuple print ("The value of currentTime is:", currentTime) # access tuple print ("The number of seconds since midnight is", \ ( currentTime[ 0 ] * 3600 + currentTime[ 1 ] * 60 +\ currentTime[ 2 ] )) Enter hour: 9 Enter minute: 16 Enter second: 1 The value of currentTime is: (9, 16, 1) The number of seconds since midnight is 33361 Creates a tuple that holds the time entered by the user Tuples are accessed using brackets Converts the time to seconds Out puts the entire tuple 16
17
Sequence Unpacking Unpacking – A useful shortcut for to assign values to multiple variables in one statement Example: – aList = [ 1, 2, 3 ] – first, second, third = aList 17
18
2002 Prentice Hall. All rights reserved. Outline Fig05_07.py # Fig. 5.7: fig05_07.py # Unpacking sequences. # create sequences aString = "abc" aList = [ 1, 2, 3 ] aTuple = "a", "A", 1 # unpack sequences to variables print ("Unpacking string...") first, second, third = aString print ("String values:", first, second, third) print ("\nUnpacking list...") first, second, third = aList print ("List values:", first, second, third) print ("\nUnpacking tuple...") first, second, third = aTuple print ("Tuple values:", first, second, third) # swapping two values x = 3 y = 4 print ("\nBefore swapping: x = %d, y = %d" % ( x, y )) x, y = y, x # swap variables print ("After swapping: x = %d, y = %d" % ( x, y ) ) Creates a sting a list and a tupleUnpacks the tuple into elementsUnpacks the string into charactersUnpacks the list into elementsThe technique can also be used to swap two items 18
19
Sequence Slicing Allows a programmer to access a portion of a string or element at once – SequenceName [ start:end ] Returns the portion of the sequence from the starting position up to the ending position String – sliceString = "abcdefghij" – sliceString[ start:end ] # answer of sliceString[1 : 3] is "bc" # answer of sliceString[-2 : -1] is "i" subscript range: [start, end-1] 19
20
2002 Prentice Hall. All rights reserved. Outline Fig05_08.py # Fig. 5.8: fig05_08.py # Slicing sequences. # create sequences sliceString = "abcdefghij" sliceTuple = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ) sliceList = [ "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X" ] # print strings print ("sliceString: ", sliceString) print ("sliceTuple: ", sliceTuple) print ("sliceList: ", sliceList) print () # get slices start = int( input( "Enter start: " ) ) end = int( input( "Enter end: " ) ) # print slices print ("\nsliceString[", start, ":", end, "] = ", \ sliceString[ start:end ] ) print ("sliceTuple[", start, ":", end, "] = ", \ sliceTuple[ start:end ] ) print ("sliceList[", start, ":", end, "] = ", \ sliceList[ start:end ] ) Creates a string a list and a tupleGets a start and end point from the user Returns only the data from the start point up to the end point 20
21
Dictionaries Key-value pairs – Unordered collection of references – Each value is referenced through key in the pair – Curley braces ({}) are used to create a dictionary – When entering values Use { key1:value1, … } Keys must be immutable values – strings, numbers and tuples Values can be of any Python data type 21
22
Operations in Dictionaries Access dictionary element – dictionaryName [key] – dictionaryName [key] = value # update the value of an existing key Add key-value pair – dictionaryName [newKey] = newValue Delete key-value pair – del dictionaryName [key] 22
23
2002 Prentice Hall. All rights reserved. Outline Fig05_09.py # Fig. 5.09: fig05_09.py # Creating, accessing and modifying a dictionary. # create and print an empty dictionary emptyDictionary = {} print ("The value of emptyDictionary is:", emptyDictionary ) # create and print a dictionary with initial values grades = { "John": 87, "Steve": 76, "Laura": 92, "Edwin": 89 } print ("\nAll grades:", grades ) # access and modify an existing dictionary print ("\nSteve's current grade:", grades[ "Steve" ] ) grades[ "Steve" ] = 90 print ("Steve's new grade:", grades[ "Steve" ] ) # add to an existing dictionary grades[ "Michael" ] = 93 print ("\nDictionary grades after modification:" ) print (grades ) # delete entry from dictionary del grades[ "John" ] print ("\nDictionary grades after deletion:" ) print (grades) Alters and displays the new grade for Steve Creates a grades dictionary using names as the key and their grade as the value Creates an empty dictionaryAdds a new name to the grades dictionary Removes the name john from the dictionary with the del keyword 23
24
List and Dictionary Methods Method – A function that performs the behaviors of an object List methods – append - add values on to the end of a list Dictionary methods – Allows manipulation of the items just as in a list 24
25
List Methods 25
26
2002 Prentice Hall. All rights reserved. Outline Fig05_13.py # Fig. 5.13: fig05_13.py # Dictionary methods. monthsDictionary = { 1 : "January", 2 : "February", 3 : "March", 4 : "April", 5 : "May", 6 : "June", 7 : "July", 8 : "August", 9 : "September", 10 : "October", 11 : "November", 12 : "December" } print ("The dictionary items are:") print (monthsDictionary.items() ) print ( "\nThe dictionary keys are:") print ( monthsDictionary.keys() ) print ("\nThe dictionary values are:") print (monthsDictionary.values() ) print ("\nUsing a for loop to get dictionary items:") for key in monthsDictionary.keys(): print ("monthsDictionary[", key, "] =", monthsDictionary[key]) Creates a dictionary with the month number as the key and the month name as the value Prints out all the items, both key and value, in the dictionary Prints out all the keys in the dictionaryPrints out just the values in the dictionary Loops though using the keys to display all the items in the dictionary 26
27
Dictionary Methods 27
28
Dictionary Methods (cont'd) 28
29
29 References and Reference Parameters Pass-by-value – Copies the value and passes the copy Pass-by-reference – Allows a function to access the caller data and to modify it – Can increase performance Prevents the copying of large data – Can weaken security Allows direct access to the data Pass by object reference – Only thing allowed in Python – Combination of pass-by-value and pass-by-reference – Can modify mutable objects and not immutable objects
30
30 Passing Lists to Functions Passing a list – The same applies for other mutable objects in Python – To pass a list, pass it without its brackets – This allows the entire list to be changed – Items in the list that are immutable (numbers or strings) cannot be changed by the function when passed individually
31
2002 Prentice Hall. All rights reserved. Outline 31 Fig05_16.py # Fig. 5.16: fig05_16.py # Passing lists and individual list elements to functions. def modifyList( aList ): for i in range( len( aList ) ): aList[ i ] *= 2 def modifyElement( element ): element *= 2 aList = [ 1, 2, 3, 4, 5 ] print ("Effects of passing entire list:") print ("The values of the original list are:") for item in aList: print (item,end=" ") modifyList( aList ) print ("\n\nThe values of the modified list are:") for item in aList: print (item,end=" ") print ("\n\nEffects of passing list element:") print ("aList[ 3 ] before modifyElement:", aList[ 3 ] ) modifyElement( aList[ 3 ] ) print ("aList[ 3 ] after modifyElement:", aList[ 3 ] ) print ("\nEffects of passing slices of list:") print ("aList[ 2:4 ] before modifyList:", aList[ 2:4 ] ) modifyList( aList[ 2:4 ] ) print ("aList[ 2:4 ] after modifyList:", aList[ 2:4 ] ) Both the modifyList and modifyElement functions take the given object and multiply them by 2 Passes the entire list, the changes in the function will affect the list Passes on element, it will not permanently be modified in the list Passes a slice of the list, the changes made are only temporary
32
Sorting and Searching Lists Sorting a list – Use the sort method Searching a list – Use the index method 32
33
2002 Prentice Hall. All rights reserved. Outline 33 Fig05_17.py Program Output # Fig. 5.17: fig05_17.py # Sorting a list. aList = [ 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 ] print ("Data items in original order") for item in aList: print (item, end=" ") aList.sort() print ("\n\nData items after sorting") for item in aList: print (item, end=" ") print() Data items in original order 2 6 4 8 10 12 89 68 45 37 Data items after sorting 2 4 6 8 10 12 37 45 68 89 The sort method is used to order the numbers in ascending order Displays the sorted listDisplays the unorganized list
34
2002 Prentice Hall. All rights reserved. Outline 34 Fig05_18.py Program Output # Fig. 5.18: fig05_18.py # Searching a list for an integer. # Create a list of even integers 0 to 198 aList = range( 0, 199, 2 ) searchKey = int(input( "Enter integer search key: " ) ) if searchKey in aList: print ("Found at index:", aList.index( searchKey ) ) else: print ("Value not found") Enter integer search key: 36 Found at index: 18 Enter integer search key: 37 Value not found The index method is used to find an item in the list and return the index of that item Creates a list containing the even numbers from 0 to 200
35
35
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.