Lecture of 20th October at 13:15 (* Create a simple function to add 1 to a value *) >>> def mfif(n): ... return n+1 (* What values will these return? *) >>> mfif(2) >>> mfif(2.0) >>> mfif("a") (* How to create an anonymous function *) >>> msif = lambda n:n+1 (* What will these return? *) >>> msif(2) >>> type(lambda n:n+1) >>> msif(2+5j) >>> msif(2.0+5.0j) (* Seeing where the function has been stored. Does the location change? *) >>> (lambda x:x) >>> (lambda x:x) (* What happens when we compare an anonymous function to itself? *) >>> (lambda x:x) == (lambda x:x) >>> (lambda x:x) is (lambda x:x) >>> x = y = (lambda x:x) >>> x == y >>> x = (lambda x:x) ; y = (lambda x:x) >>> x == y (* What does this print out? Why is the result interesting? *) >>> [lambda x:x]*(10**3) (* Lists in python are mutable. What will this output? *) >>> l = [lambda x:x]*4+[lambda x:x]*4 >>> l[0] = 4 >>> l (* We can print a sorted version of a list without changing the original list *) >>> l = list(range(4,-1,-1)) >>> sorted(l) >>> l (* Sorting works lexicographically on character lists. What will this return? *) >>> sorted(["a","A","bb"]) (* Single and double quotes are synonymous in Python *) >>> ("a",'a') (* But single and double quotes have different lexicographical values. What will this return? *) >>> '"a"' == "'a'" (* Creating a list which holds every value from 0 to 99 *) >>> [ x*x for x in range(100) ] (* This notation can be used with two "for" loops. This returns a chess board *) >>> [ (x,y) for x in range(8) for y in range(8) ] (* This function will return true if the number is odd, and false if the number is even. Uses binary comparison *) >>> 5&1 >>> not(5&1) >>> not(4&1) (* How to delete items from a list *) >>> x = [1,2,3,4,5] >>> del x[0] >>> x >>> del x[-1] >>> x (* Python lists have a sort-in-place method. What will these return? *) >>> x = [5,4,3,2,1] >>> x.sort() >>> x >>> x = [4,5,1,3,2] >>> x.sort() >>> x >>> x = [[5,3],[3,4],[1,2]] >>> x.sort() >>> x