Python Lists and Such CS 4320, SPRING 2015 List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds x to the end of list s s.pop(i) removes and returns the element at index I ◦ s.pop() is the same as s.pop(-1) x in s and x not in s test for containment del s[i:j:k] removes a slice (or a single element) s.insert(i,x) inserts x at index i 1/7/2015 CS 4320, SPRING 2015 2 Command Line Parameters When a program is run from the command line, parameters can be added. Parameters can also be provided when running in PyCharm (most IDE’s support this feature as well) The parameters are made available in a list named sys.argv To use the arguments, include the line import sys at the beginning of the script The values of the arguments are of type string The parameter at index 0 is always the path to the script 1/7/2015 CS 4320, SPRING 2015 3 Examples Get the list of values from the command line Apply the various functions and print the results 1/7/2015 CS 4320, SPRING 2015 4 Tuples Tuples are immutable lists As literals, tuples are given by a comma separated list of values surrounded by parentheses ◦ (1,2,3) Beware! ◦ (1) is not a tuple, it is simply the integer 1 ◦ (1,) is a tuple with one element, the integer 1 Tuples turn up in some places, especially as the return values from some functions. ◦ Just be aware that tuples cannot be modified 1/7/2015 CS 4320, SPRING 2015 5 Dictionaries Also known as ‘hash maps’, ‘associative memory’, and ‘maps’ A dictionary associates keys to values A literal dictionary uses curly braces with pairs ‘key:value’ Indexing retrieves values for a given key 1/7/2015 CS 4320, SPRING 2015 6 Examples Create some dictionaries and access values Demonstrate what happens when access is attempted with a key not present 1/7/2015 CS 4320, SPRING 2015 7 Dictionary Functions d.get(key) gets the value associated with key d.get(key,y) gets the value associated with key, returns y if there is none key in d returns true if key is in dictionary d d.keys() returns an ‘iterable’ of the keys in d (will use with loops) del d[key] deletes the key from the dictionary 1/7/2015 CS 4320, SPRING 2015 8 Examples Use the various functions and display the results 1/7/2015 CS 4320, SPRING 2015 9 Comprehensions A syntactical shortcut for creating lists from other lists [ expr for var in list ] This can be extended with more ‘for’ clauses Filters can be added with ‘if’ clauses 1/7/2015 CS 4320, SPRING 2015 10 Examples Create some list comprehensions Create a list from a range by applying a simple expression Modify the comprehension to select based on remainder modulo something Create a list of pairs (x,y) where x divides y evenly 1/7/2015 CS 4320, SPRING 2015 11