CS2304: Sequences and Collections
Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for item in mylist:). Python has 5 built-in sequence types. In this set of slides we ll talk about: The str, tuple, and list sequences/collections. There are also bytearray and bytes sequence types. We may discuss these later in the semester.
First Some Review: Strings A collection of characters ex. Hello World. Single and double quotes are pretty much interchangeable: So Hello World is the same as Hello World. While or are acceptable, they do need to match so won t work. Remember can be used for multi-line comments. Strings in Python are for the most part very flexible. + Will concatenate two or more strings. * Can be used as well, ex. hello *3.
Review: String Basics Strings can use bracket notation like arrays/ strings in other languages. >>> s = Hello World >>> s[0] H >>> s[3] l Oddly, at least coming from another language, you can also use negative indices. You start at the end of the string and count backwards: >>> s[-1] d
Review: String Slicing String slicing is supported, giving you substrings: >>> s = Hello World >>> s[0:3] Hel >>> s[3:6] lo Strings are immutable, so trying to modify an individual cell will cause an error: >>> s[0] = L # TypeError You can always create another string though.
Review: Iterating Through Strings Recall: We can use a for loop to move through a string. for x in s: print(x) The loop will iterate through the characters, printing them one by one: H e l
Our Next Sequence: Tuples You can think of a tuple as being kind of a like a C struct. Or like a Java class with only data items and without member functions. You can group several different types together into a collection. So, you can have a tuple with a string, a number, and a boolean value. Or tuple made up of lists and other tuples. Each item in the tuple is an object reference. Tuples are built-in into Python and can be created without formally defining a new data type. Tuples, like strings, are also immutable.
Creating And Using Tuples To create a tuple you just list values separated by commas: >>> t = hello, 1, True Parentheses are often used but not required: >>> t = ( hello, 1, True) You can return tuples: # at the end of a function return ( hello, 1, True) # elsewhere t = func() You can also capture the individual values: x, y, z = func()
Tuples: Accessing The Items Like strings, you can use bracket notation: >>> t = ( Hello, 1, True) >>> t[0] Hello >>> t[2] True Negative indexes work too, you count from the back or end of the tuple: >>> t[-1] True
Tuple Slicing Slicing is supported, giving you sub-tuples: >>> t = ( hello, 1, True) >>> t[0:1] ('hello',) >>> t[1:3] (1, True) Like strings, tuples are immutable, so trying to modify an individual item will cause an error: >>> t[0] = L # TypeError You can always create another tuple though: >>> t = t[0:1] # Works fine
Iterating Through Tuples These work just like they did with strings: for x in t: print(x) The loop will iterate through the items, printing them one by one: hello 1 True
Other Useful Tuple Information Tuples support a few useful functions: t.count(x) - gives you the number times x occurs in the tuple. t.index(x) - gives you the index of the left most occurrence of x. >>> t = ( hello, 1, True) >>> t.count( hello ) 1 >>> t.index(true) 1 # because 1 counts as true >>> t = ( hello, 0, True) >>> t.index(true) 2
More (Hopefully) Useful Information You can use the + operator with tuples as well: >>> t = ( hello, 1, True) >>> f = t[0:1] + ( balloons,) + t[1:3] >>> f ('hello', 'balloons', 0, True) Of course, this is actually creating another tuple. The membership operator works with tuples: >>> if hello in t:... print( We found it. ) We found it. >>> if world in t:... print( We found it. ) >>>
Passing Tuples To Functions There are a few ways to pass tuples to functions, one is fairly straightforward: >>> t = ( hello, 1, True) >>> func(t) # elsewhere def func(var): # break apart the tuple here msg = var[0]+ str(var[1]) # use the pieces of the tuple
Passing Tuples To Functions You can also expand the tuple automatically using the *: # note this function has 3 parameters def func2(x, y, z): # do something x, y, and z pass # call the function using the tuple # remember the tuple has 3 elements >>> func2(*t) Trying this with the tuple f(which has 4 items) will result in an error.
Now We Move On To Lists A list is an ordered sequence of zero or more object references. Very flexible, if performance isn t crucial lists will often take the place of what we traditionally think of as an arrays job. There is an array type we will examine later. Since each item is an object reference, elements don t have to be the same type. Lists, like tuples, are built-in into Python and can be created very easily. Lists are mutable, unlike like strings and tuples.
Basic List Usage We ve seen this in class before, but this creates an empty list: >>> l = [] We ve also seen examples like this in projects: >>> rates = [.10,.15,.25] You can have different data types in the same list as well as nested lists: >>> l = [ hello, 1, True, [.10,.15,.25]]
List Slicing CS2304: Python for Java Programmers Slicing is supported, giving you sub-lists: >>> l = [ hello, 1, True, [.10,.15,.25]] >>> l[0:3] ['hello', 1, True] >>> l[2:4] [True, [0.1, 0.15, 0.25]] Lists are mutable, so trying to modify an individual cell works as you would expect: >>> l[0] = L # Works fine >>> l[2] = W # Also works fine >>> l ['L', 1, 'W', [0.1, 0.15, 0.25]]
Iterating Through Lists Recall: We can use a for loop to move through a list. for x in l: print(x) The loop will iterate through the items, printing them one by one: L 1 W
List Functions Like tuples, lists support count and index: l.count(x) - gives you the number times x occurs in the list. l.index(x) - gives you the index of the left most occurrence of x. >>> l = [ hello, 1, True] >>> l.count( hello ) 1 >>> l.index(true) 1 # because 1 counts as true >>> l = [ hello, 0, True] >>> l.index(true) 2
More List Functions Lists support far more functions than just count and index. l.append(x) - appends item x at the end of l. l.insert(i, x) - inserts item x at index i. l.pop() - removes the right most value in l. l.remove(x) - removes the left most occurrence of x. l.reverse() - reverses the order of l in-place. Take a look at the book or resources online for more functions.
More (Hopefully) Useful Information You can use the + operator with lists as well: >>> l = [] >>> l += [1, hello ] >>> l += [[1, 2, 3]] >>> l [1, 'hello', [1, 2, 3]] The membership operator works with lists: >>> if hello in l:... print( We found it. ) We found it. >>> if world in l:... print( We found it. ) >>>
List Comprehensions Let s say you d like to quickly create a list filed with data, you could do something like this: l = [] for x in range(10): l.append(x**2) >>> l [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] This accomplishes the same thing: l =[x**2 for x in range(10)]
More List Comprehensions You can do far more interesting things with list comprehensions: [(x, y) for x in [1,2,3] for y in [3,1,4] if x!= y] This (more complex code) accomplishes the same thing: l = [] for x in [1, 2, 3]: for y in [3, 1, 4]: if x!= y: l.append((x,y)) >>> l [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
Other Uses For List Comprehensions As filters: l = [-1, -2, 0, 2, 4] pos = [x for x in l if x >=0] >>> pos [0, 2, 4] They also work with functions, and types other than numbers: >>> from math import pi >>> [str(round(pi, i)) for i in range(1, 6)] ['3.1', '3.14', '3.142', '3.1416', '3.14159']
One More Collection: Dictionaries The types we ve looked at are groupings of values that you could access via l[0] or t[0]. Regardless of type, an index (a number) is a common way to access the collections we ve seen so far. Python also has a mapping or associative array type called a dictionary. Instead of being indexed by numbers, a dictionary is indexed using keys. So a dictionary is made up of (unordered) key & value pairs. A key can be any immutable type, so strings, numbers, and tuples (if they don t contain any mutable objects).
Creating And Using Dictionaries To create an empty dictionary you use curly brackets or braces: >>> m = {} To create dictionary a with some starting values: >>> m = { hello :1, world :2} You can then use m kind of like an array: >>> m[ hello ] 1 You can add new items using the same method: m[ foobar ] = 3
Dictionaries: Other Useful Functions If you want to test whether something is the dictionary you can use get: # j is not a key in the map, get will # return None if doesn t find the key >>> m.get( j ) is None True >>> m.get( hello ) is not None True There are functions to get the keys and the values: >>> list(m.keys()) >>> list(m.values())
Iterating Through Dictionaries You can use for loops to iterate through all of the key, value pairs for k, v in m.items(): print(k, v) hello 1 world 2 foobar 3 If you want to delete a individual piece of the dictionary: del m[ hello ]