0% found this document useful (0 votes)
69 views

Programming in Python

The document discusses Python sequences like lists, tuples, and dictionaries. It covers creating, accessing, and modifying sequence elements as well as differences between lists and tuples. Examples demonstrate unpacking sequences into variables and using sequences like lists to create histograms from user input.

Uploaded by

James Alpha
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Programming in Python

The document discusses Python sequences like lists, tuples, and dictionaries. It covers creating, accessing, and modifying sequence elements as well as differences between lists and tuples. Examples demonstrate unpacking sequences into variables and using sequences like lists to create histograms from user input.

Uploaded by

James Alpha
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 35

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
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
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
Sequences
• Sequences
– Series of items that are often related
– Strings are sequences in Python
– A sequence is returned by the range function

4
Example of Sequences
C[0] -45 C[-12]
C[1] 6 C[-11]
Name sequence C[2] 0 C[-10]
(C)
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]
Position number of
C[9] 10 C[-3]
the element within
sequence C C[10] 40 C[-2]
C[11] 33 C[-1]
5
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
Creating Sequences – String
• Strings
– Use quotes
• string1 = "hello"
– Empty string
• string2 = ""

7
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
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
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
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
# Fig. 5.3: fig05_03.py Outline
# Creating, accessing and changing a list.

aList = [] # create empty list


Fig05_03.py
# add values to list
for number in range( 1, 11 ):
aList += [ number ] Adds the values 1 to 10 to the list
print ("The value of aList is:", aList)

# access list values by iteration


print ("\nAccessing values by iteration:")
Prints the list, both all at
for item in aList: once and one at a time
print (item, end=" ")

print ()

# access list values by index


print ("\nAccessing values by index:")
print ("Subscript Value") Prints the list in
for i in range( len( aList ) ):
comparison to its
print ("%9d %7d" % ( i, aList[ i ] )) subscripts
# modify list
print ("\nModifying a list value...")
print ("Value of aList before modification:", aList) Sets the value of the first item to -100
aList[ 0 ] = -100
aList[ -3 ] = 19
print ("Value of aList after modification:", aList) Sets the value of the 8th item to 19

 2002 Prentice Hall.


All rights reserved.
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.

13
14
# Fig. 5.5: fig05_05.py Outline
# Creating a histogram from a list of values.

values = [] # a list of values


Fig05_05.py
# input 10 values from user
print ("Enter 10 integers:")

for i in range( 10 ):
newValue = int( input( "Enter integer %d: " % ( i + 1 ) ) )
values += [ newValue ]
Prompts the user for 10 integers
# 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 ] ))

Outputs as many *’s as


the number entered into
the list by the user

 2002 Prentice Hall.


All rights reserved.
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
# Fig. 5.6: fig05_06.py Outline
# Creating and accessing tuples.

# retrieve hour, minute and second from user


hour = int( input( "Enter hour: " ) ) Fig05_06.py
minute = int( input( "Enter minute: " ) )
second = int( input( "Enter second: " ) )
Creates a tuple that holds
currentTime = hour, minute, second # create tuple the time entered by the user
print ("The value of currentTime is:", currentTime) Out puts the entire tuple
# access tuple
print ("The number of seconds since midnight is", \ Tuples are accessed
( currentTime[ 0 ] * 3600 + currentTime[ 1 ] * 60 +\ using brackets
currentTime[ 2 ] ))

Converts the time to seconds


Enter hour: 9 Program Output
Enter minute: 16
Enter second: 1
The value of currentTime is: (9, 16, 1)
The number of seconds since midnight is 33361

 2002 Prentice Hall.


All rights reserved.
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
# Fig. 5.7: fig05_07.py Outline
# Unpacking sequences.

# create sequences
aString = "abc" Fig05_07.py
aList = [ 1, 2, 3 ] Creates a sting a list and a tuple
aTuple = "a", "A", 1

# unpack sequences to variables


print ("Unpacking string...")
first, second, third = aString Unpacks the string into characters
print ("String values:", first, second, third)

print ("\nUnpacking list...")


first, second, third = aList
print ("List values:", first, second, third)
Unpacks the list into elements

print ("\nUnpacking tuple...") Unpacks the tuple into elements


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 )) The technique can also be


x, y = y, x # swap variables used to swap two items
print ("After swapping: x = %d, y = %d" % ( x, y ) )

 2002 Prentice Hall.


All rights reserved.
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" subscript range:
– sliceString[ start:end ] [start, end-1]
• # answer of sliceString[1 : 3] is "bc"
• # answer of sliceString[-2 : -1] is "i"

19
20
# Fig. 5.8: fig05_08.py Outline
# Slicing sequences.

# create sequences
sliceString = "abcdefghij" Fig05_08.py
sliceTuple = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 )
Creates a string a list and a tuple
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: " ) ) Gets a start and end
end = int( input( "Enter end: " ) ) point from the user
# print slices
print ("\nsliceString[", start, ":", end, "] = ", \
sliceString[ start:end ] )
Returns only the data from the
print ("sliceTuple[", start, ":", end, "] = ", \
sliceTuple[ start:end ] ) start point up to the end point

print ("sliceList[", start, ":", end, "] = ", \


sliceList[ start:end ] )

 2002 Prentice Hall.


All rights reserved.
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
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
# Fig. 5.09: fig05_09.py Outline
# Creating, accessing and modifying a dictionary.

# create and print an empty dictionary Creates an empty dictionaryFig05_09.py


emptyDictionary = {}
print ("The value of emptyDictionary is:", emptyDictionary )
Creates a grades dictionary
# create and print a dictionary with initial values
grades = { "John": 87, "Steve": 76, "Laura": 92, "Edwin": 89 }
using names as the key and
print ("\nAll grades:", grades ) their grade as the value
# access and modify an existing dictionary
print ("\nSteve's current grade:", grades[ "Steve" ] )
grades[ "Steve" ] = 90 Alters and displays the
print ("Steve's new grade:", grades[ "Steve" ] )
new grade for Steve
# add to an existing dictionary Adds a new name to the
grades[ "Michael" ] = 93 grades dictionary
print ("\nDictionary grades after modification:" )
print (grades )
Removes the name john from the
# delete entry from dictionary dictionary with the del keyword
del grades[ "John" ]
print ("\nDictionary grades after deletion:" )
print (grades)

 2002 Prentice Hall.


All rights reserved.
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
List Methods
Method Purpose
append( item ) Inserts item at the end of the list.
count( element ) Returns the number of occurrences of element in
the list.
extend( newList ) Inserts the elements of newList at the end of the
list.
index( element ) Returns the index of the first occurrence of
element in the list. If element is not in the list, a
ValueError exception occurs. [Note: We
discuss exceptions in Chapter 12, Exception
Handling.]
insert( index, item ) Inserts item at position index.
pop( [index] ) Parameter index is optional. If this method is
called without arguments, it removes and returns
the last element in the list. If parameter index is
specified, this method removes and returns the
element at position index.
remove( element ) Removes the first occurrence of element from
the list. If element is not in the list, a
ValueError exception occurs.
reverse() Reverses the contents of the list in place (rather
than creating a reversed copy).
sort( [compare- Sorts the content of the list in place. The
function] ) optional parameter compare-function is a
function that specifies the compare criteria. The
compare-function takes any two elements of the
list (x and y) and returns -1 if x should appear
before y, 0 if the orders of x and y do not matter
and 1 if x should appear after y. [Note: We
discuss sorting in Section 5.9.] 25
Fig. 5.12 List methods.
26
# Fig. 5.13: fig05_13.py Outline
# Dictionary methods.

monthsDictionary = { 1 : "January", 2 : "February", 3 : "March",


4 : "April", 5 : "May", 6 : "June", 7 : "July", Fig05_13.py
8 : "August", 9 : "September", 10 : "October",
11 : "November", 12 : "December" }

print ("The dictionary items are:") Creates a dictionary with the


print (monthsDictionary.items() ) Prints out all the items,
month both keyas the key and
number
and value, in the the
dictionary
month name as the value
print ( "\nThe dictionary keys are:")
print ( monthsDictionary.keys() ) Prints out all the keys in the dictionary
print ("\nThe dictionary values are:")
print (monthsDictionary.values() ) Prints out just the values in the dictionary
print ("\nUsing a for loop to get dictionary items:")

for key in monthsDictionary.keys():


print ("monthsDictionary[", key, "] =", monthsDictionary[key])

Loops though using the


keys to display all the
items in the dictionary

 2002 Prentice Hall.


All rights reserved.
Dictionary Methods
Method Description
clear() Deletes all items from the dictionary.
copy() Creates and returns a shallow copy of the
dictionary (the elements in the new
dictionary are references to the elements
in the original dictionary).
get( key [, returnValue] ) Returns the value associated with key. If
key is not in the dictionary and if
returnValue is specified, returns the
specified value. If returnValue is not
specified, returns None.
has_key( key ) Returns 1 if key is in the dictionary;
returns 0 if key is not in the dictionary.
items() Returns a list of tuples that are key-value
pairs.
keys() Returns a list of keys in the dictionary.
popitem() Removes and returns an arbitrary key-
value pair as a tuple of two elements. If
dictionary is empty, a KeyError
exception occurs. [Note: We discuss
exceptions in Chapter 12, Exception
Handling.] This method is useful for
accessing an element (i.e., print the key-
value pair) before removing it from the
dictionary. 27
Dictionary Methods (cont'd)
setdefault( key [, Behaves similarly to method get. If key is
dummyValue] ) not in the dictionary and dummyValue is
specified, inserts the key and the specified
value into dictionary. If dummyValue is
not specified, value is None.
update( newDictionary ) Adds all key-value pairs from
newDictionary to the current dictionary
and overrides the values for keys that
already exist.
values() Returns a list of values in the dictionary.
iterkeys() Returns an iterator of dictionary keys.
[Note: We discuss iterators in Appendix
O, Additional Python 2.2 Features.]
iteritems() Returns an iterator of key-value pairs.
[Note: We discuss iterators in Appendix
O, Additional Python 2.2 Features.]
itervalues() Returns an iterator of dictionary values.
[Note: We discuss iterators in Appendix
O, Additional Python 2.2 Features.]
Fig. 5.14 Dictionary methods.

28
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

29
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

30
31
# Fig. 5.16: fig05_16.py Outline
# Passing lists and individual list elements to functions.

def modifyList( aList ):


Fig05_16.py
for i in range( len( aList ) ):
aList[ i ] *= 2 Both the modifyList and
def modifyElement( element ):
modifyElement functions
element *= 2 take the given object and
multiply them by 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=" ")
Passes the entire list, the changes
modifyList( aList ) in the function will affect the list
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 ] )
Passes on element, it will not
modifyElement( aList[ 3 ] ) permanently be modified in the list
print ("aList[ 3 ] after modifyElement:", aList[ 3 ] )

print ("\nEffects of passing slices of list:")


print ("aList[ 2:4 ] before modifyList:", aList[ 2:4 ] ) Passes a slice of the list, the
modifyList( aList[ 2:4 ] ) changes made are only temporary
print ("aList[ 2:4 ] after modifyList:", aList[ 2:4 ] )
 2002 Prentice Hall.
All rights reserved.
Sorting and Searching Lists
• Sorting a list
– Use the sort method
• Searching a list
– Use the index method

32
33
# Fig. 5.17: fig05_17.py Outline
# Sorting a list.

aList = [ 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 ]


Fig05_17.py
print ("Data items in original order")

for item in aList: Displays the unorganized list


print (item, end=" ")
The sort method is used to order
aList.sort() the numbers in ascending order
print ("\n\nData items after sorting")

for item in aList:


print (item, end=" ") Displays the sorted list
print()

Data items in original order Program Output


2 6 4 8 10 12 89 68 45 37
 
Data items after sorting
2 4 6 8 10 12 37 45 68 89

 2002 Prentice Hall.


All rights reserved.
34
# Fig. 5.18: fig05_18.py Outline
# Searching a list for an integer.

# Create a list of even integers 0 to 198 Creates a list containing the


aList = range( 0, 199, 2 ) even numbers from 0 to Fig05_18.py
200
searchKey = int(input( "Enter integer search key: " ) )

if searchKey in aList:
print ("Found at index:", aList.index( searchKey ) )
else:
The index method is used
print ("Value not found") to find an item in the list
and return the index of that
item
Enter integer search key: 36
Found at index: 18 Program Output

Enter integer search key: 37


Value not found

 2002 Prentice Hall.


All rights reserved.
35

You might also like