5.37. Group Work: Functions with Tuples and Dictionaries

It is best to use a POGIL approach with the following. In POGIL students work in groups on activities and each member has an assigned role. For more information see https://cspogil.org/Home.

Note

If you work in a group, have only one member of the group fill in the answers on this page. You will be able to share your answers with the group at the bottom of the page.

Learning Objectives

Students will know and be able to do the following.

Content Objectives:

Process Objectives:

5.37.1. Tuples

A tuple is like a list in that holds items in order and those items are separated by commas. They can be enclosed in (), but don’t have to be.

Run this code to see what it prints.

5.37.2. Tuples are Immutable

Unlike lists, tuples are immutable (can not change). This makes them more efficient than lists which can change.

Q-7: Look at the Python code below. What do you think will happen when you run the following code?

Run this code to see what it prints.

Note

Tuples are immutable (not changeable), so you will get an error if you try to change them.

Some functions that work on lists return an iterator (an object that you can loop through the values of) which you can convert to a list of tuples using the list function. The range function also returns an iterator.

Run this code to see what it prints.

Note

The zip function takes two lists and returns an iterator. You can convert this iterator to a list of tuples using the list function. Each tuple has an element from list1 and an element from list2 in order.

5.37.3. Dictionaries

A dictionary stores a value for a key.

Run this code to see what it prints.

Q-13: Look at the Python code below. What do you think will happen when you run the following code?

Run this code to see what it prints.

There is another way to update the value for a key that works even if the key isn’t in the dictionary already.

Run this code to see what it prints.

Note

The better way to increment a count at a key is to use dict[key] = dict.get(key,0) + 1. This will avoid a key error if the key isn’t in the dictionary and the code is shorter.

If you worked in a group, you can copy the answers from this page to the other group members. Select the group members below and click the button to share the answers.

The Submit Group button will submit the answer for each each question on this page for each member of your group. It also logs you as the official group submitter.

You have attempted of activities on this page