# Tuples --- CS 65 // 2021-04-01 ## Extra Credit Activities - [Drake's Got Talent](https://calendar.drake.edu/event/drakes_got_talent?utm_source=newsletter&utm_medium=email&utm_content=https%3A//d31hzlhk6di2h5.cloudfront.net/20210330/37/d7/7f/18/d0461f71e982682339189262_352x354.jpeg&utm_campaign=Staff-March-30#.YGJQSGRKg-Q) + Thursday, April 1 at 5pm + Helmick Commons - [Civic Action Week](https://www.drake.edu/community/learningservice/studentopportunities/civicactionweek/) - Drake Relays ## Weekend Review Sessions - One of the CS 65 tutors (David Tennant) is considering hosting a weekly review session - Would any of you be interested in such review sessions? # Extra Credit Assignment - Optional, individual, assignment on images - Your solutions will count as extra credit # Questions ## ...about anything? # Tuples ## The `tuple` Type - **Purpose:** + To express *immutable* lists of values - **Express:** + Tuples are written: `(1,2,3)` and `("CS", 65)` - **Operations:** + Virtually identical to `list` + No methods for mutation like `append` or `pop` + Expressions like `t[0] = 100` don't work ## Tuple Assignment - One common use of tuples is to assign multiple elements at the same time ```py x, y = point.getX(), point.getY() ``` - You can also do this with lists: ```py r, g, b = img.getPixel(x, y) # [255, 0, 0] ``` - What happens if the number of variables and elements don't match up? ```py r, g, b = [100, 200, 300, 400] ``` ## Using Tuples as Keys in a Dictionary - Since tuples are immutable, they can be used as keys in a dictionary ```py d = dict() first = "Titus" last = "Klinge" d[first,last] = 56 ``` ## Lists of Tuples - It is common to create lists of tuples, such as a list of `(x,y)` coordinates ```py >>> points = [(3,4), (0, 1), (2, 7), (9,1)] ``` - Suppose I want to find the point that has the **largest y coordinate** ## Lists of Tuples - Here is a first attempt at a solution: ```py def largest_y_coord(points): largest = points[0] for p in points: if p[1] > largest[1]: largest = p return largest ``` ## Lists of Tuples - Here is an approach using the `sorted` function ```py def second(tup): return tup[1] def largest_y_coord(points): sorted_points = sorted(points, key=second) return sorted_points[-1] ``` ## Sorting Lists of Contacts - Suppose I encode contacts like the following: ```py # First, Last, Occupation Birth City sam = ("Samwise", "Gamgee", "Gardener", "The Shire") frodo = ("Frodo", "Baggins", "Ring Bearer", "The Shire") titus = ("Titus", "Klinge", "Higher Ed", "Rivendell") ``` ## Sorting Lists of Contacts - Then we can write access functions such as: ```py def first_name(contact): return contact[0] def last_name(contact): return contact[1] def occupation(contact): return contact[2] def birth_city(contact): return contact[3] ``` ## Sorting Lists of Contacts - Given a list of contacts such as: ```py >>> contacts = [sam, frodo, titus] ``` - We can sort the list by first name by using: ```py >>> contacts.sort(key = first_name) ``` - Or by last name: ```py >>> contacts.sort(key = last_name) ``` # Self Checks ## Word Frequencies - Recall that we wrote two procedures that help us count the number of times a word is used in a book ## Word Frequencies - The following function extracts all the words out of a file and packages them up in a list ```py def parse_words(filename): list_of_words = [] f = open(filename) for line in f: line = line.strip() list_of_words.append(line) f.close() return list_of_words ``` ## Word Frequencies - The following creates a dictionary mapping every word to the frequency of which it occurs in the list ```py def count_words(list_of_words): d = dict() for word in list_of_words: if word in d: d[word] = d[word] + 1 else: d[word] = 1 return d ``` ## Word Frequencies - Suppose I want to sort the words **by their frequency** to determine the most frequently used words - We can do this using the following: ```py def second(pair): return pair[1] def sort_words(list_of_words): d = count_words(list_of_words) return sorted(d.items(), key=second) ``` ## Zipping Lists Together - It is often useful to perform on operation on the elements of two or more sequences of numbers - For example, we might want to add two rows of a spreadsheet like this: ```py >>> t1 = [100, 200, 300] >>> t2 = [1, 2, 3] >>> add_lists(t1, t2) [101, 202, 303] ``` ## Zipping Lists Together - Here is a first attempt that we might try: ```py def add_lists(t1, t2): new_list = [] for i in range(range(len(t1))): s = t1[i] + t2[i] new_list.append(s) return new_list ``` - What happens if the length of `t1` and `t2` are different? ## Zipping Lists Together - What does the `zip` function do? - Here is a solution using `zip`: ```py def add_lists(t1, t2): new_list = [] for x, y in zip(t1, t2): new_list.append(x + y) return new_list ``` ## The `enumerate` Function - What does the `enumerate` function do? - It allows us to iterate over a sequence's indices and elements at the same time ```py t = ["abc", "def", "ghi"] for index, element in enumerate(t): print("index =", index) print("element = ", element) ``` - This is often useful so we don't confuse the index of an element in a list with the element itself