Transcript aList[2]
Sequences
• A sequence (same as array in e.g. Java) is a list of elements
– The range function returns a sequence
>>> range(3, 12)
>>> [3, 4, 5, 6, 7, 8, 9, 10, 11]
>>>
• Sequence elements
– 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!
– Strings are sequences in Python
1
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.
2
Creating Sequences
• Creations
– Strings
• Use quotes: string1 = ""
– Lists
• Use brackets; separate multiple items with a comma
• list1 = []
• list2 = [ 1, 7, 66 ]
– Tuples
• Use parentheses; separate multiple items with a comma
• tuple1 = ()
• tuple2 = ( 19, 27 )
• this is a one element tuple/singleton:
singleton = 1,
• may ignore parentheses: tuple3 = 5,10,15
3
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
4
Adding items to a list
aList = []
# create empty list
# add values to list
for number in range( 1, 11 ):
aList += [ number ]
Adds the values 1 to 10 to the list
(by adding a new list with one
element to the existing list in
each round)
• Using the + operator, you need to add a list to a list:
- aList += [ number ]
• Using the append method, you add an element to the list:
- aList.append( number )
for i in .. ?
Two ways of accessing all elements in a sequence
startlist = [‘John’,‘George’, …,‘Wayne’]
# list with 10.000 items
for i in range( len( values ) ):
# here we get the subscript, so we can output things like
# ‘Bobby has index 8427’:
print “%s has index %d” %( startlist[i], i )
for item in values:
# here we get the item directly, but not the subscript
print item
Sequence unpacking - assigning values to multiple
variables in one statement
•# create sequences
aString = "abc"
aList = [ 1, 2, 3 ]
aTuple = "a", "A", 1
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
# swapping two values
x = 3
y = 4
Unpacks the list into elements
Unpacks the tuple into elements
Sequence unpacking can
also be used to swap two
items (neat!)
print "\nBefore swapping: x = %d, y = %d" % ( x, y )
x, y = y, x
# swap variables
print "After swapping: x = %d, y = %d" % ( x, y )
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
Sequence Slicing
• Allows access to a portion of a string or other sequence
theSequence[ start:end ]
• Returns new sequence with the portion of the original
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 = ‘Sibyl saw Basil lying there'
>>> print aString[12:18]
sil ly
>>>
>>> print aString[0:len(aString)/2]
# printing half the string
Sibyl saw Bas
8
List Methods
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
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.]
Fig. 5.12 List m ethod s.
9
gcd_function_test.py
Testing your function
•
Sequence unpacking
•
for/else construct
10
gcd_function2_test.py
New implementation of function, same test
11
Dictionaries
• Dictionaries
–
–
–
–
Mapping that consists of unordered key-value pairs
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
12
Creates an empty dictionary
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" ]
# 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
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
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" ]
# 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}
Dictionary Methods
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.
15
dictionary
shallowCopy
deepCopy
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
16
Passing Lists to Functions
• 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)
17
def modifyList( aList ): # multiply all elements in the list by 2
for i in range( len( aList ) ):
No type
aList[ i ] *= 2
def modifyElement( element ): # multiply single element by 2
element *= 2
aList = [ 1, 2, 3, 4, 5 ]
modifyList( aList )
Passes the entire list, the
changes in the function
will affect the list
print "\n\nThe values of the modified list are:"
declaration, so
function body
assumes it gets
a list! NB: good
documentation
helps you use
your function as
intended, no
compiler to help
you
for item in aList:
print item,
print "aList[ 3 ] before modifyElement:", aList[ 3 ]
modifyElement( aList[ 3 ] )
print "aList[ 3 ] after modifyElement:", aList[ 3 ]
Passes a single element, it
will not permanently be
modified in the list
Passes a slice of the list,
print "aList[ 2:4 ] before modifyList:", aList[ 2:4 ] no permanent change to
list
modifyList( aList[ 2:4 ] )
print "aList[ 2:4 ] after modifyList:", aList[ 2:4 ]
def modifyList( aList ): # multiply all elements in the list by 2
for i in range( len( aList ) ):
aList[ i ] *= 2
def modifyElement( element ):
element *= 2
aList = [ 1, 2, 3, 4, 5 ]
modifyList( aList )
The values of the modified list are:
2 4 6 8 10
aList[ 3 ] before modifyElement: 8
aList[ 3 ] after modifyElement: 8
aList[ 2:4 ] before modifyList: [6, 8]
aList[ 2:4 ] after modifyList: [6, 8]
print "\n\nThe values of the modified list are:"
for item in aList:
print item,
print "aList[ 3 ] before modifyElement:", aList[ 3 ]
modifyElement( aList[ 3 ] )
print "aList[ 3 ] after modifyElement:", aList[ 3 ]
print "aList[ 2:4 ] before modifyList:", aList[ 2:4 ]
modifyList( aList[ 2:4 ] )
print "aList[ 2:4 ] after modifyList:", aList[ 2:4 ]