Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sequences A sequence is a list of elements Lists and tuples

Similar presentations


Presentation on theme: "Sequences A sequence is a list of elements Lists and tuples"— Presentation transcript:

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 Access element with sequenceName[ subscript ] Subscripts may be negative Slicing works same way as with strings

2 Creating Sequences Creations Strings Lists Tuples Use quotes: s = ""
Use brackets list1 = [] list2 = [ 1, 7, 66 ] Tuples Use parentheses tuple1 = () Tuple2 = 5, tuple3 = ( 19, 27 )

3 for item in .. ? Two ways of accessing all elements in a sequence
startlist = [‘John’,‘George’, …,‘Wayne’] # long list for i, name in enumerate( startlist ): # here we get both the subscript and the item: print “%s has index %d” %( name, i ) for name in startlist: # here we get the item directly, but not the subscript print name

4 The xrange function The built-in xrange function returns a list
Indexing as with slicing: “From a up to but not including b” >>> xrange(3, 12) >>> [3, 4, 5, 6, 7, 8, 9, 10, 11] >>> >>> xrange(5) >>> [0, 1, 2, 3, 4] >>> xrange(1, 10, 2) >>> [1, 3, 5, 7, 9] >>> xrange(10, 1, -3) >>> [10, 7, 4]

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

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

7 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 "<stdin>", line 1, in ? TypeError: object doesn't support item assignment

8 Passing a list as an argument to a function
passing_lists_to_functions.py sum and max functions

9 Output passing_lists_to_functions.py
Top 3 of the grades [10, 5, 11, 5, 13, 5] are: [13, 11, 10] Average grade: 5

10 Explanation passing_lists_to_functions.py [ , , , , , ] grades 5 11 13
10 5 5

11 Explanation passing_lists_to_functions.py a [ , , , , , ] grades 5 11
13 10 5 5

12 Better way of finding topN from a list of numbers
Algorithm: Don’t find the max N times: Inefficient! Keep a sorted list of current top-N Go through given list one number at a time If number is greater than current N’th greatest, insert in correct position

13 Better way of finding topN from a list of numbers
Want to compare to top‘s N’th element, so top must be initialized with N values Make sure any value can enter top topN.py top 11 10 5 4 n 5 i

14 Output topN.py - current top4: [10, 4, 4, 4]
Top 4 of the grades [10, 5, 11, 5, 13, 5] are: [13, 11, 10, 5] Average grade: 8.17

15 Functions working on lists
map reduce filter zip

16 Unelegant way of finding length of longest string
longest_string_in_list.py Don’t call len twice!

17 Elegant way using map longest_string_in_list2.py
map: applies given function (first argument) to all elements in given sequence (second argument), returns list with results

18 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

19 Sequence unpacking – testing a function
for/else construct gcd_function_test.py

20 New implementation of function, same test
gcd_function2_test.py

21 Dictionaries Dictionaries
Mapping that consists of unordered key-value pairs Each value is referenced though its key Curly braces {} are used to create a dictionary Creating a dictionary: { key1:value1, … } or: dict( [ (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

22 Dictionary example: DNA dinucleotides
List comprehension: Create list of all tuples a, b where a and b are from nuc gcd_function_test.py Dictionary method fromkeys: Create dictionary with keys from the given list and all values 0 Iterate through s, update dictionary value for each dinucleotide key Dictionary method iteritems: Iterate through (a sorted copy of) all of d’s key/value pairs. The keys are tuples, the values are integers. Add report string to histogram list, convert to string and return

23 Output gcd_function_test.py Input DNA string: atcagcgatattcgatcagctag

24 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

25 On to the exercises..


Download ppt "Sequences A sequence is a list of elements Lists and tuples"

Similar presentations


Ads by Google