1 of 27

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

2 of 27

Objectives

  • In this chapter, you will:
    • Understand Python sequences
    • Learn the list AND dictionary data types
    • Know how to create, initialize, and refer to individual elements of lists, 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 of 27

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 of 27

Sequences

  • Sequences
    • Series of items that are often related
    • Strings are sequences in Python
    • A sequence is returned by the range function

4

5 of 27

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

6 of 27

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 of 27

Creating Sequences – String

  • Strings
    • Use quotes
      • string1 = "hello"
    • Empty string
      • string2 = ""

7

8 of 27

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 of 27

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

9

10 of 27

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

11 of 27

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

12 of 27

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

13 of 27

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

13

14 of 27

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]

14

15 of 27

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

16 of 27

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

16

17 of 27

List Methods

17

18 of 27

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

19 of 27

Dictionary Methods

19

20 of 27

Dictionary Methods (cont'd)

20

21 of 27

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

21

22 of 27

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

22

23 of 27

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

24 of 27

Sorting and Searching Lists

  • Sorting a list
    • Use the sort method
  • Searching a list
    • Use the index method

24

25 of 27

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

26 of 27

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 of 27

27