Transcript Sequences

Sequences
• A sequence is a list of elements
• Lists and tuples
– Lists mutable
– Tuples immutable
• Sequence elements can be indexed with subscripts
– First index is 0
– Obtain element with sequenceName[ subscript ]
– Subscripts may be negative
– Slicing works same way as with strings
1
The range function
• The built-in range function returns a sequence
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
range(3, 12)
[3, 4, 5, 6, 7, 8, 9, 10, 11]
range(5)
[0, 1, 2, 3, 4]
range(1, 10, 2)
[1, 3, 5, 7, 9]
range(10, 1, -3)
[10, 7, 4]
2
Creating Sequences
• Creations
– Strings
• Use quotes:
s = ""
– Lists
• Use brackets
• list1 = []
• list2 = [ 1, 7, 66 ]
– Tuples
• Use parentheses
• tuple1 = ()
• tuple2 = ( 19, 27 )
4
Using Lists and Tuples
• Only difference between lists and tuples is:
– Lists are mutable, tuples are immutable
>>>
>>>
>>>
[3,
aList = [3, 6, 9]
aList[2] = 141
aList
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
5
Adding items to a list
aList = []
# create empty list
# add values to list
for number in range( 1, 11 ):
aList += [ 1.0/number ]
Adds the values 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( startlist ) ):
# 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 startlist:
# here we get the item directly, but not the subscript
print item
longest_string_in_list.py
Finding length of longest string in list
•
randrange function: picks random
number from sequence which would be
produced by range with the same
parameters
8
longest_string_in_list2.py
Finding length of longest string in list using map
•
map function: applies given function (first
argument) to all elements in given sequence
(second argument), returns list with results
•
max function: can maximize over entire list
9
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
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.
12
gcd_function_test.py
Testing a function
•
Sequence unpacking
•
for/else construct
13
gcd_function2_test.py
New implementation of function, same test
14
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 anything
– Add item to dictionary d with d[key] = value
15
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 addition:"
print grades
# delete entry from dictionary
del grades[ "John" ]
print "\nDictionary grades after deletion:"
print grades
Creates a grades dictionary
using names as keys and their
grades as values
Alters and displays the
new grade for Bill
Adds a new name to the
grades dictionary
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 addition:"
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 addition:
{'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
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.
18
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
19
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)
20
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 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 ]
On to the exercises..
23