Transcript a[2, 3]

1
5.2 Sequences
• Sequence (also called arrays in e.g. Java)
– Series of items that are often related
– Strings are sequences in Python
– The range function returns a sequence
>>> range(3, 12)
>>> [3, 4, 5, 6, 7, 8, 9, 10, 11]
>>>
– Elements/items in the sequence
• Referred to by subscripts; the first is always zero
• Obtain one by using sequenceName[ subscript ]
• Can also be referred to negatively
– -1 would be the last element of the sequence!
 2002 Prentice Hall. All rights reserved.
2
5.2 Sequences
Name sequence (c)
Position number of the
element within sequence
c
Fig. 5.1
c[ 0 ]
-45
c[ -12 ]
c[ 1 ]
6
c[ -11 ]
c[ 2 ]
0
c[ -10 ]
c[ 3 ]
72
c[ -9 ]
c[ 4 ]
1543
c[ -8]
c[ 5 ]
-89
c[- 7 ]
c[ 6 ]
0
c[ -6 ]
c[ 7 ]
62
c[ -5 ]
c[ 8]
-3
c[ -4 ]
c[ 9 ]
1
c[- 3 ]
c[ 10 ]
6453
c[ -2 ]
c[ 11 ]
-78
c[ -1 ]
Sequence with elements and indices.
 2002 Prentice Hall. All rights reserved.
3
5.3 Creating Sequences
• Creations
– Strings
• Use quotes
• string1 = ""
– Lists
• Use brackets
• Separate multiple items with a comma
• list1 = []
– Tuples
• Use parentheses
• Separate multiple items with a comma
• tuple = ()
• singleton = 1, - this is a one element tuple or a singleton
 2002 Prentice Hall. All rights reserved.
4
5.4 Using Lists and Tuples
• Differences
– Lists are mutable, tuples are immutable
>>>
>>> aList = [3, 6, 9]
>>> aList[2] = 141
>>> aList
[3, 6, 141]
>>>
>>> aTuple = (3, 6, 9)
>>> aTuple[2] = 141
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>>
– Tuples and lists can both contain the same data
– Most often used for different purposes
 2002 Prentice Hall. All rights reserved.
5
5.4.1 Using Lists
• Lists
– Not restricted to values of the same type, but ..
• .. mostly used to hold data of the same type
(Java: arrays declared to hold items of same type)
– The length is not usually predetermined and can vary
throughout the program
– Accessing elements out of range
• Python exits and an out of range error is displayed
Python 2.2b2 (#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
 2002 Prentice Hall. All rights reserved.
6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# 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 ]
Fig05_03.py
Adds the values 1 to 10 to the list
print "The value of aList is:\n", aList
# access list values by iteration
print "\nAccessing values by iteration:"
for item in aList:
print item,
Prints the list, both all at
once and one at a time
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 ] )
Prints the list in
comparison to its
subscripts
# modify list
print "\nModifying a list value..."
print "Value of aList before modification:\n", aList
aList[ 0 ] = -100
aList[ -3 ] = 19
print "Value of aList after modification:\n", aList
Sets the value of the first item to -100
Sets the value of the 8th item to 19
 2002 Prentice Hall.
All rights reserved.
7
# 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:\n", aList
# access list values by iteration
print "\nAccessing values by iteration:"
for item in aList:
print item,
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:\n", aList
aList[ 0 ] = -100
aList[ -3 ] = 19
print "Value of aList after modification:\n", aList
The value of aList is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Accessing values by iteration:
1 2 3 4 5 6 7 8 9 10
Accessing values by index:
Subscript
Value
0
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
10
Modifying a list value...
Value of aList before modification:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Value of aList after modification:
[-100, 2, 3, 4, 5, 6, 7, 19, 9, 10]
 2002 Prentice Hall.
All rights reserved.
8
Another example
Fig05_05.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 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( raw_input( "Enter integer %d: " % ( i + 1 ) ) )
values += [ newValue ]
Prompts the user for 10 integers
# create histogram, starting with the headline
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.
9
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
10 integers:
integer 1: 19
integer 2: 3
integer 3: 15
integer 4: 7
integer 5: 11
integer 6: 9
integer 7: 13
integer 8: 5
integer 9: 17
integer 10: 1
Fig05_05.py
Program Output
Creating a histogram from values:
Element
Value Histogram
0
19 *******************
1
3 ***
2
15 ***************
3
7 *******
4
11 ***********
5
9 *********
6
13 *************
7
5 *****
8
17 *****************
9
1 *
 2002 Prentice Hall.
All rights reserved.
10
for i in .. ?
Two obvious ways of accessing all elements in a sequence
values = [5, 19, 7, 3, 23]
subscripts_items.py
for i in range( len( values ) ):
.. # here we get the subscript, so we can output things like
# ‘the 3. element is 7’
for i in values:
.. # here we get the item directly, but not the subscript
 2002 Prentice Hall.
All rights reserved.
11
5.4.2 Using Tuples
• Tuples
– Used to contain data that is related but not necessarily of the
same type
• Each data item represents a unique piece of the overall portion
– In this case tuples are usually not iterated though
– The needed data is known before creating the tuple, e.g. a
person’s name, age and birth date
• Again this is not required but is a general rule
 2002 Prentice Hall. All rights reserved.
12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Fig. 5.6: fig05_06.py
# Creating and accessing tuples.
# retrieve hour, minute and second from
hour = int( raw_input( "Enter hour: " )
minute = int( raw_input( "Enter minute:
second = int( raw_input( "Enter second:
currentTime = hour, minute, second
user
)
" ) )
" ) )
# create tuple
print "The value of currentTime is:", currentTime
Fig05_06.py
Creates a tuple that holds
the time entered by the user
(NB: the commas create the
tuple, parentheses optional!)
# 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
Tuples are also
accessed using
brackets
Converts the time to seconds
Program Output
 2002 Prentice Hall.
All rights reserved.
13
Sequence unpacking - A useful shortcut to assign values
to multiple variables in one statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Fig. 5.7: fig05_07.py
# Unpacking sequences.
# create sequences
aString = "abc"
aList = [ 1, 2, 3 ]
aTuple = "a", "A", 1
Fig05_07.py
Creates a string, a list and a tuple
# unpack sequences to variables
print "Unpacking string..."
first, second, third = aString
print "String values:", first, second, third
Unpacks the string into characters
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
Unpacks the list into elements
Unpacks the tuple into elements
# 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 )
The technique can also be
used to swap two items
(neat!)
 2002 Prentice Hall.
All rights reserved.
14
Sequence unpacking - A useful shortcut to assign values
to multiple variables in one statement
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Fig. 5.7: fig05_07.py
# Unpacking sequences.
Fig05_07.py
# 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
Unpacking string...
String values: a b c
Unpacking list...
List values: 1 2 3
Unpacking tuple...
Tuple values: a A 1
Before swapping: x = 3, y = 4
After swapping: x = 4, y = 3
output
# 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 )
 2002 Prentice Hall.
All rights reserved.
15
5.4.4 Sequence Slicing
• Slicing
– Allows access to a portion of a string or other sequence at once
– theSequence [ start:end ]
– Returns the portion of the sequence from the starting position
up to (but not including) the ending position
>>>
>>> aTuple = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> print aTuple[2:4]
(2, 3)
>>> print aTuple[1:9]
(1, 2, 3, 4, 5, 6, 7, 8)
>>> print aTuple[-3:-1]
(7, 8)
>>>
>>> aString = 'elementary, my dear Watson'
>>> print aString[13:17]
y de
>>>
>>> print aString[0:len(aString)/2]
# printing half the string
elementary, m
 2002 Prentice Hall. All rights reserved.
16
5.5 Dictionaries
• Dictionaries
– Mapping that consists of key-value pairs
• Referred to as hashes or maps in other languages
–
–
–
–
Unordered collection of references
Each value is referenced though its key
Curley braces ({}) are used to create a dictionary
Creating a dictionary: { key1:value1, … }
– Keys must be immutable values such as strings, numbers and
tuples
– Values can be of any Python data type
 2002 Prentice Hall. All rights reserved.
17
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Fig. 5.09: fig05_09.py
# Creating, accessing and modifying a dictionary.
Fig05_09.py
# create and print an empty dictionary
Creates an empty
emptyDictionary = {}
print "The value of emptyDictionary is:", emptyDictionary
# create and print a dictionary with initial values
grades = { "John": 87, "Bill": 76, "Laura": 92, "Edwin": 89 }
print "\nAll grades:", grades
# access and modify an existing dictionary
print "\nBill's current grade:", grades[ "Bill" ]
grades[ "Bill" ] = 90
print "Bill's new grade:", grades[ "Bill" ]
dictionary
Creates a grades dictionary
using names as the key and
their grade as the value
Alters and displays the
new grade for Bill
Adds a new name to the
grades dictionary (simply set
the value of the new key)
Removes the name john from the
dictionary with the del keyword
# 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
 2002 Prentice Hall.
All rights reserved.
18
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# create and print an empty dictionary
emptyDictionary = {}
print "The value of emptyDictionary is:", emptyDictionary
Fig05_09.py
# create and print a dictionary with initial values
grades = { "John": 87, "Bill": 76, "Laura": 92, "Edwin": 89 }
print "\nAll grades:", grades
# access and modify an existing dictionary
print "\nBill's current grade:", grades[ "Bill" ]
grades[ "Bill" ] = 90
print "Bill's new grade:", grades[ "Bill" ]
# 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
The value of emptyDictionary is: {}
All grades: {'Edwin': 89, 'John': 87, 'Bill': 76, 'Laura': 92}
Note: unordered!
(‘Michael’ not
inserted at the
end)
Bill's current grade: 76
Bill's new grade: 90
Dictionary grades after modification:
{'Edwin': 89, 'Michael': 93, 'John': 87, 'Bill': 90, 'Laura': 92}
Dictionary grades after deletion:
{'Edwin': 89, 'Michael': 93, 'Bill': 90, 'Laura': 92}
 2002 Prentice Hall.
All rights reserved.
19
5.6 List and Dictionary Methods
• List methods
– append - add values on to the end of a list
– A list of methods is provided in Fig. 5.12
• Dictionary methods
– Allows manipulation of the items just as in a list
– A list of methods is provided in Fig. 5.14
 2002 Prentice Hall. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
method
append
# Fig. 5.10: fig05_10.py
# Appending items to a list.
playList = []
# list of favorite plays
print "Enter your 5 favorite Shakespearean plays.\n"
for i in range( 5 ):
playName = raw_input( "Play %d: " % ( i + 1 ) )
playList.append( playName )
print "\nSubscript
Value"
Fig05_10.py
Has the user enter 5 plays
Appends the items onto the list
using the append method
for i in range( len( playList ) ):
print "%9d
%-25s" % ( i + 1, playList[ i ] )
Displays the items
for the user
Enter your 5 favorite Shakespearean plays.
Play
Play
Play
Play
Play
1:
2:
3:
4:
5:
Richard III
Henry V
Twelfth Night
Hamlet
King Lear
Subscript
1
2
3
4
5
Program Output
Value
Richard III
Henry V
Twelfth Night
Hamlet
King Lear
 2002 Prentice Hall.
All rights reserved.
20
1
2
3
4
5
6
7
8
9
10
11
12
# Fig. 5.11: fig05_11.py
# Student poll program.
responses = [ 1,
1,
6,
5,
print "Rating
2,
6,
5,
6,
6,
3,
7,
7,
4,
8,
6,
5,
8,
6,
8,
6,
5, 9, 7, 8, 10,
10, 3, 8, 2, 7,
6, 7, 5, 6, 6,
4, 8, 6, 8, 10 ]
Frequency"
for i in range( 1, 11 ):
print "%6d %13d" % ( i, responses.count( i ) )
Rating
1
2
3
4
5
6
7
8
9
10
Frequency
2
2
2
2
5
11
5
7
1
3
method
count
Creates a list of 40 numbers
from 1 through 10
Uses the count method to tally up
the total of each number in the lint
Fig05_11.py
Program Output
 2002 Prentice Hall.
All rights reserved.
21
22
5.6 List Methods
cf. the
comparable
interface in
Java
Method
Purp o se
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( [comparefunction] )
Sorts the content of the list in place. The optional parameter
compare-function is a function that specifies the compare
Fig. 5.12 List m ethod s.
 2002 Prentice Hall. All rights reserved.
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.]
23
Intermezzo
1. Write a function list_minmax which takes a
list as an argument, sorts it and returns a tuple
with the minimum and maximum values (see
pages 178 and 180).
2. Call the function on 10 lists of different lengths
with random numbers between 1 and 1000 (see
on page 162 how to add a number to a list) and
print the results.
 2002 Prentice Hall. All rights reserved.
24
import random
solution
def list_minimax(aList):
aList.sort()
return aList[0], aList[ len(aList)-1 ]
for i in range(10):
mylist = []
# create empty list
length = random.randrange( 5, 11 )
# choose length of list
while length > 0:
mylist += [ random.randrange (1, 1001) ]
# add random element to list
length -= 1
min, max = list_minimax( mylist )
# unpack the returned tuple
print mylist, " -- min, max: %d, %d" %(min, max)
[4, 356, 587, 589, 604, 660, 711, 824, 873, 971] -- min, max: 4, 971
[83, 159, 231, 389, 760, 989] -- min, max: 83, 989
[151, 176, 404, 780, 894] -- min, max: 151, 894
..
 2002 Prentice Hall. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 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()
dictionary
methods
Creates a dictionary with
the month number as the
key and the month name
as the value
Prints out all items, both key and value
print "\nThe dictionary keys are:"
print monthsDictionary.keys()
print "\nThe dictionary values are:"
print monthsDictionary.values()
Prints out all the keys in the dictionary
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 ]
25
Fig05_13.py
Loops though using the
keys to display all the
items in the dictionary
 2002 Prentice Hall.
All rights reserved.
26
The dictionary items are:
[(1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'),
(6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10,
'October'), (11, 'November'), (12, 'December')]
The dictionary keys are:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Fig05_13.py
Program Output
The dictionary values are:
['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December']
Using a for loop to get dictionary items:
monthsDictionary[ 1 ] = January
monthsDictionary[ 2 ] = February
monthsDictionary[ 3 ] = March
monthsDictionary[ 4 ] = April
monthsDictionary[ 5 ] = May
monthsDictionary[ 6 ] = June
monthsDictionary[ 7 ] = July
monthsDictionary[ 8 ] = August
monthsDictionary[ 9 ] = September
monthsDictionary[ 10 ] = October
monthsDictionary[ 11 ] = November
monthsDictionary[ 12 ] = December
 2002 Prentice Hall.
All rights reserved.
27
5.6 Dictionary Methods – part of fig 5.14
Method
De sc rip tio n
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 Key-
Error 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.
 2002 Prentice Hall. All rights reserved.
28
Shallow vs. Deep Copy
>>> dictionary = { "listKey" : [ 1, 2, 3 ] }
>>> shallowCopy = dictionary.copy()
# make a shallow copy
>>>
>>> dictionary[ "listKey" ].append( 4 )
>>>
>>> print dictionary
{'listKey': [1, 2, 3, 4]}
>>>
>>> print shallowCopy
{'listKey': [1, 2, 3, 4]}
>>> from copy import deepcopy
>>> deepCopy = deepcopy( dictionary )
>>>
>>> dictionary[ "listKey" ].append( 5 )
>>>
>>> print dictionary
{'listKey': [1, 2, 3, 4, 5]}
>>>
>>> print shallowCopy
{'listKey': [1, 2, 3, 4, 5]}
>>>
>>> print deepCopy
{'listKey': [1, 2, 3, 4]}
# make a deep copy
Fig. 5.15 Difference between a shallow copy and a deep copy.
 2002 Prentice Hall. All rights reserved.
29
5.7 Passing values to functions
• 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 – side effects
• Python: Pass by object reference
– Combination of pass-by-value and pass-by-reference..
 2002 Prentice Hall. All rights reserved.
30
5.8 Passing Lists to Functions
• To pass a list pass it without its brackets
• Original list can be changed by the function
• Items in the list that are immutable (numbers or
strings) cannot be changed by the function when
passed individually
• In general: mutable objects can be changed when
passed to a function (lists, dictionaries),
immutable objects cannot (strings, tuples,
numbers)
 2002 Prentice Hall. All rights reserved.
31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Fig. 5.16: fig05_16.py
# Passing lists and individual list elements to functions.
Fig05_16.py
def modifyList( aList ): # multiply all elements in the list by 2
for i in range( len( aList ) ):
Again: no type declaration, so
aList[ i ] *= 2
function body assumes it
gets a list! NB: good documentation helps you use your
function as intended, no help from a compiler
def modifyElement( element ):
element *= 2
# multiply single element 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,
modifyList( aList )
Passes the entire list, the changes
in the function will affect the list
print "\n\nThe values of the modified list are:"
for item in aList:
print item,
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 ]
Passes an element, it will not
permanently be modified in the list
Passes a slice of the list, no
permanent changeto2002
listPrentice Hall.
All rights reserved.
32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Fig. 5.16: fig05_16.py
# Passing lists and individual list elements to functions.
def modifyList( aList ): # multiply all elements in the list by 2
for i in range( len( aList ) ):
aList[ i ] *= 2
Fig05_16.py
def modifyElement( element ):
element *= 2
# multiply single element 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,
modifyList( aList )
print "\n\nThe values of the modified list are:"
for item in aList:
print item,
Effects of passing entire list:
The values of the original list are:
1 2 3 4 5
The values of the modified list are:
2 4 6 8 10
Effects of passing list element:
aList[ 3 ] before modifyElement: 8
aList[ 3 ] after modifyElement: 8
Effects of passing slices of list:
aList[ 2:4 ] before modifyList: [6, 8]
aList[ 2:4 ] after modifyList: [6, 8]
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 ]
 2002 Prentice Hall.
All rights reserved.
33
Sorting a list with the sort() method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Fig05_17.py
# 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,
aList.sort()
Displays the unorganized list
The sort method is used to order
the numbers in ascending order
print "\n\nData items after sorting"
for item in aList:
print item,
print
Displays the sorted list
Program Output
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
 2002 Prentice Hall.
All rights reserved.
34
Searching a list with the index() method
1
2
3
4
5
6
7
8
9
10
11
12
# 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 )
Fig05_18.py
Creates a list containing the
even numbers from 0 to 198
number = int( raw_input( "Enter integer number: " ) )
Easy way to check if some element appears in a list
if number in aList:
print "Found at index:", aList.index( number )
else:
print "Value not found"
Enter integer number: 36
Found at index: 18
The index method is used to
find an item in the list and
return the index of that
item. If it is not there, you
get an error
Program Output
Enter integer number: 37
Value not found
 2002 Prentice Hall.
All rights reserved.
41
Writing and testing a function
When writing a function myfunction, think thus:
1. What should myfunction do?
–
Think in terms of input/output: on this input it should give this output.
Don't include any interaction with the user in the actual function.
2. How do I know that myfunction works?
–
Choose a representative list of input and corresponding correct output: if
myfunction works on these, it works.
3. Automatic testing.
–
Write another function test_function that explicitly calls
myfunction on every input from the above list and checks the output.
The test_function should not change even if you change the
implementation of myfunction . If you discover errors, leave the input
for which the function failed in the list so that you can see that your
function works after you fix the bug.
•
In most cases, this strategy is applicable, wise, and encouraged!
 2002 Prentice Hall. All rights reserved.
42
Deitel exercise 4.4c (see course homepage)
Write a function that determines whether a number
is a prime. Let's call it is_prime.
1. is_prime should take an integer n>0 as input and
return 1 if n is a prime and 0 otherwise.
2. There are infinitely many primes so we can't check all of
them. But it should return 1 for all this input: 2, 3, 5, 7,
19, 31, 137, 881, and it should return 0 for all this input:
9, 14, 77, 100, 169.
3. Put all these input/output checks in test_function
 2002 Prentice Hall. All rights reserved.
43
First solution
import math
def is_prime(c):
for i in range(2, int(math.sqrt(c))):
if c%i == 0:
return 0
return 1
# why is this enough?
def test_function():
# list of input/output tuples:
inout = [(2, 1), (5, 1), (7, 1), (19, 1), (31, 1), (137, 1), (881, 1),
(9, 0), (14, 0), (77, 0), (100, 0), (169, 0)]
for input, output in inout:
if is_prime(input) != output:
print "oops: input %d gave wrong output" %input
if __name__== "__main__":
test_function() # this code not executed when file imported as a module
 2002 Prentice Hall. All rights reserved.
44
Running the test
threonine:~% python ex4_4.py
oops: input 9 gave wrong output
oops: input 169 gave wrong output
Hmm.. Well, 9 and 169 are quadratic numbers, do we check
for their squareroots 3 and 13?
def is_prime(c):
for i in range(2, int(math.sqrt(c))): #oops, +1
if c%i == 0:
return 0
return 1
 2002 Prentice Hall. All rights reserved.
45
import math
Revised solution
def is_prime(c):
for i in range(2, 1 + int(math.sqrt(c))):
if c%i == 0:
return 0
return 1
def test_function(): # KEEP the test function instead you change is_prime
inout = [(2, 1), (5, 1), (7, 1), (19, 1), (31, 1), (137, 1), (881, 1),
(9, 0), (14, 0), (77, 0), (100, 0), (169, 0)]
for input, output in inout:
if is_prime(input) != output:
print "oops: input %d gave wrong output" %input
if __name__=="__main__":
# test_function()
Either import this module from another program that handles the user
interaction, or place any user interaction in the name/main wrapper
 2002 Prentice Hall. All rights reserved.