Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Sequences A sequence is a list of elements Lists and tuples – Lists mutable – Tuples immutable Sequence elements can be indexed with subscripts – First.

Similar presentations


Presentation on theme: "1 Sequences A sequence is a list of elements Lists and tuples – Lists mutable – Tuples immutable Sequence elements can be indexed with subscripts – First."— Presentation transcript:

1 1 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

2 2 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]

3 3 Sequences Fig. 5.1Sequence with elements and indices. -45 6 0 72 1543 -89 0 62 -3 1 6453 -78c[ 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 ]

4 4 Creating Sequences Creations – Strings Use quotes: s = "" – Lists Use brackets list1 = [] list2 = [ 1, 7, 66 ] – Tuples Use parentheses tuple1 = () tuple2 = ( 19, 27 )

5 5 Using Lists and Tuples Only difference between lists and tuples is: – 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 " ", line 1, in ? TypeError: object doesn't support item assignment

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

7 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 for i in.. ? Two ways of accessing all elements in a sequence

8 8 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

9 9 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

10 # 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 tupleUnpacks the tuple into elementsUnpacks the string into charactersUnpacks the list 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!)

11 11 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

12 12 List Methods

13 13 gcd_function_test.py Testing a function Sequence unpacking for/else construct

14 14 gcd_function2_test.py New implementation of function, same test

15 15 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

16 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 Alters and displays the new grade for Bill Creates a grades dictionary using names as keys and their grades as values Creates an empty dictionaryAdds a new name to the grades dictionary Removes the name john from the dictionary with the del keyword

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

18 18 Dictionary Methods

19 19 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 ) # 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]} dictionary shallowCopy deepCopy

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

21 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 be modified in the 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 Passes a slice of the list, no permanent change to list

22 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]

23 23 On to the exercises..


Download ppt "1 Sequences A sequence is a list of elements Lists and tuples – Lists mutable – Tuples immutable Sequence elements can be indexed with subscripts – First."

Similar presentations


Ads by Google