CSCI/CMPE 4341 Topic: Programming in Python�Chapter 6: Lists, and Dictionaries
Xiang Lian
The University of Texas – Pan American
Edinburg, TX 78539
lianx@utpa.edu
1
Objectives
2
Introduction
3
Sequences
4
Example of Sequences
C[0] | -45 | C[-12] |
C[1] | 6 | C[-11] |
C[2] | 0 | C[-10] |
C[3] | 72 | C[-9] |
C[4] | 34 | C[-8] |
C[5] | 39 | C[-7] |
C[6] | 98 | C[-6] |
C[7] | -1345 | C[-5] |
C[8] | 939 | C[-4] |
C[9] | 10 | C[-3] |
C[10] | 40 | C[-2] |
C[11] | 33 | C[-1] |
Name sequence (C)
Position number of the element within sequence C
5
Sequences (cont'd)
6
Creating Sequences – String
7
Creating Sequences – List
8
Lists
9
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 -100
Sets the value of the 8th item to 19
10
© 2002 Prentice Hall.�All rights reserved.
Outline
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 "<stdin>", line 1, in ?
IndexError: list index out of range
Fig. 5.4 Out-of-range error.
11
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
12
© 2002 Prentice Hall.�All rights reserved.
Outline
Dictionaries
13
Operations in Dictionaries
# update the value of an existing key
14
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 dictionary
Adds a new name to the grades dictionary
Removes the name john from the dictionary with the del keyword
15
© 2002 Prentice Hall.�All rights reserved.
Outline
List and Dictionary Methods
16
List Methods
17
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 dictionary
Prints out just the values in the dictionary
Loops though using the keys to display all the items in the dictionary
18
© 2002 Prentice Hall.�All rights reserved.
Outline
Dictionary Methods
19
Dictionary Methods (cont'd)
20
References and Reference Parameters
21
Passing Lists to Functions
22
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 ] )
23
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
© 2002 Prentice Hall.�All rights reserved.
Outline
Sorting and Searching Lists
24
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()
25
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 list
Displays the unorganized list
© 2002 Prentice Hall.�All rights reserved.
Outline
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")
26
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
© 2002 Prentice Hall.�All rights reserved.
Outline
27