Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sequences The range function returns a sequence

Similar presentations


Presentation on theme: "Sequences The range function returns a sequence"— Presentation transcript:

1 Sequences The range function returns a sequence
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] >>>

2 Sequences -45 6 72 1543 -89 62 -3 1 6453 -78 c[ 11 ] c[ 10 ] c[ 9 ]
72 1543 -89 62 -3 1 6453 -78 c[ 11 ] c[ 10 ] c[ 9 ] c[ 8] c[ 7 ] c[ 4 ] c[ 3 ] c[ 2 ] c[ 1 ] c[ 0 ] c[ 6 ] c[ 5 ] Position number of the element within sequence c Name sequence (c) c[ -1 ] c[ -11 ] c[ -10 ] c[ -9 ] c[ -8] c[- 7 ] c[ -4 ] c[- 3 ] c[ -2 ] c[ -6 ] c[ -5 ] c[ -12 ] Fig. 5.1 Sequence with elements and indices.

3 Creating Sequences Creations Strings Lists Tuples
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

4 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

5 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 )

6 for i in .. ? Two ways of accessing all elements in a sequence
startlist = [‘John’,‘George’, …,‘Wayne’] # list with 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

7 Sequence unpacking - assigning values to multiple variables in one statement
# 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 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!)

8 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

9 List Methods

10 Testing your function gcd_function_test.py Sequence unpacking
for/else construct gcd_function_test.py

11 New implementation of function, same test
gcd_function2_test.py

12 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

13 Creates an empty dictionary
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:" 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

14 Note: unordered! (‘Michael’ not inserted at the end)
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:" 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)

15 Dictionary Methods

16 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 >>> from copy import deepcopy >>> deepCopy = deepcopy( dictionary ) # make a deep copy >>> dictionary[ "listKey" ].append( 5 ) {'listKey': [1, 2, 3, 4, 5]} >>> print deepCopy shallowCopy deepCopy

17 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)

18 Passes a slice of the list, no permanent change to list
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 ] 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 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

19 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: aList[ 3 ] before modifyElement: 8 aList[ 3 ] after modifyElement: 8 aList[ 2:4 ] before modifyList: [6, 8] aList[ 2:4 ] after modifyList: [6, 8]


Download ppt "Sequences The range function returns a sequence"

Similar presentations


Ads by Google