Tuples

A tuple is another of Python's sequence data types.

A tuple consists of a number of values separated by commas.

Tuples are Immutable

A tuple is a sequence of values of any type, indexed by integers. Similar to a list, but a tuple is immutable, thus it cannot be modified once created.

A multi-value tuple

A single-value tuple

If the tuple contains a single value only, then you must include the comma after the value.

This distinction is subtle so careful since you may wind up with something else.

An empty tuple

To create an empty tuple, use () as a shortcut to tuple().

tuple()

The tuple() function is useful when you want to create a tuple from another sequence.

Access a tuple element

Most list operators can be used with tuples as well.

[]

Use the [] operator to index an element.

[:]

Use a slice to index one or more elements and return a tuple with the selected elements.

Reassign a tuple

Recall that tuples are immutable, so attempting to change an element will raise an error.

You can however reassign the variable a new tuple.

Compare tuples

One tuple is compared to another by comparing respective elements from each tuple until a decision can be made.

Assign a tuple

Tuple assignment can be used in a lot of interesting ways, like swapping two values. Traditionally, this would require three variables.

Notice the way a and b are initialized using a tuple, and also swapped using a tuple.

The right hand side expression can be any sequence as well.

Here the split() method is used to return a list of elements that are assigned to the variables on the left hand side.

Return a tuple

Using a tuple you can effectively return more than a single value from a function.

Let's look at an example of a function that returns the quotient and remainder.

Python actually offers just such a function, divmod().

Here's a function that returns the min and max values of an iterable as a tuple.

Variable-Length Argument Tuples

Functions often can accept a variable number of arguments. To define such a function use a * in front of the parameter name, usually named args by convention.

The * basically gathers all the arguments into a tuple.

The reverse is also possible, i.e. you can scatter a tuple into its individual elements.

This is useful is you have a function that accepts a fixed number of parameters, and you want to use a tuple as the argument.

Recall how min() and max() are able to accept a variable number of arguments. The sum() function is an exception, since it accepts an iterable as its first argument instead.

Let's define the sumAll() function that can handle more than two arguments.

Lists and Tuples

zip() is a built-in function that takes two or more sequences and returns an iterator of tuples. Each tuple contains corresponding elements from each list.

zip is in reference to a zipper and how it works, not some compression utility.

Use a for to iterate through the tuples themselves.

If you want to get a list of tuples instead, use list().

If the sequences are of different lengths, the result has the same length as the shorter one.

You can also use tuple assignment.

Combining zip(), for and tuple assignment, you get a useful idiom for traversing two or more sequences at the same time.

The following example returns True if two corresponding (same index) elements match. False otherwise.

enumerate()

If you have a sequence and would like to traverse the elements and their indices, use the built-in function enumerate().

Dictionaries and Tuples

Use the items() method of a dictionary object to return an iterator of tuples, where each tuple is a key-value pair.

You can go the other way as well. You can create a dictionary from a list of tuples.

Combining zip() with dict() gives us a nice way to create dictionary objects.

Recall that a dictionary key must be hashable and thus immutable. A tuple meets both criteria and so can be used as a key.

Let's look at how we can use a tuple as a key to set up a telephone directory.

Practice problems

Create a separate Python source file (.py) in VSC to complete each exercise.

Download the file CROSSWD.TXT and rename it words.txt. This file includes official crosswords and you will need it for the exercises.


p1: mostFrequent.py

Write a function called mostFrequent() that takes a string and prints the letters in decreasing order of frequency.


p2: anagramSets.py

  1. Write a program that reads a word list from a file (words.txt) and prints all the sets of words that are anagrams.

    Here is an example of what the output might look like:

    ['deltas', 'desalt', 'lasted', 'salted', 'slated', 'staled']
     ['retainers', 'ternaries']
     ['generating', 'greatening']
     ['resmelts', 'smelters', 'termless']
    

    Hint: you might want to build a dictionary that maps from a collection of letters to a list of words that can be spelled with those letters. The question is, how can you represent the collection of letters in a way that can be used as a key?

  2. Modify the previous program so that it prints the longest list of anagrams first, followed by the second longest, and so on.

  3. In Scrabble, a "bingo" is when you play all seven tiles in your rack, along with a letter on the board, to form an eight-letter word. What collection of eight letters forms the most possible bingos? Hint: there are seven.

[Dictionaries] [TOC] [Data Structures Case Study]