190 likes | 201 Views
Sequences. A sequence (same as array in e.g. Java) is a list of elements The range function returns a sequence Sequence elements Referred to by subscripts; the first is always zero Obtain one by using sequenceName [ subscript ] Can also be referred to negatively
E N D
Sequences • A sequence (same as array in e.g. Java) is a list of elements • The range function returns a sequence • 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 >>> range(3, 12) >>> [3, 4, 5, 6, 7, 8, 9, 10, 11] >>>
c[ 0 ] -45 c[ -12 ] c[ 1 ] 6 c[ -11 ] Name sequence (c) 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 ] Position number of the element within sequence c c[ 9 ] 1 c[- 3 ] c[ 10 ] 6453 c[ -2 ] c[ 11 ] -78 c[ -1 ] Sequences Fig. 5.1 Sequence with elements and indices.
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
Using Lists and Tuples • Differences • Lists are mutable, tuples are immutable • Tuples and lists can both contain the same data >>> >>> 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 >>>
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) Adding items to a list • 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 )
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 for i in .. ? Two ways of accessing all elements in a sequence
# 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 # 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 ) Creates a string, a list and a tuple Unpacks the string into characters Unpacks the list into elements Unpacks the tuple into elements Sequence unpacking - assigning values to multiple variables in one statement 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 unpacking can also be used to swap two items (neat!)
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
Testing your function • Sequence unpacking • for/else construct gcd_function_test.py
New implementation of function, same test gcd_function2_test.py
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
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 an empty 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
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} 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} Note: unordered! (‘Michael’ not inserted at the end)
Shallow vs. Deep Copy dictionary >>> 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 ) # make a deep copy >>> >>> 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]} shallowCopy deepCopy
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)
def modifyList( aList ): # multiply all elements in the list by 2 for i in range( len( aList ) ): aList[ i ] *= 2 def modifyElement( element ): # multiply single element by 2 element *= 2 aList = [ 1, 2, 3, 4, 5 ] modifyList( aList ) 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 ] Passes the entire list, the changes in the function will affect the list Passes a single element, it will not permanently be modified in the list Passes a slice of the list, no permanent change to list No type declaration, so function body assumes it gets a list! NB: good documentation helps you use your function as intended, no compiler to help you
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 ) 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 ] 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]