Tuples
Objectives
- Differentiate between tuples and lists in Python, emphasizing the immutability of tuples.
- Recognize the use of tuples to group related data together.
- Learn how to create tuples
- Access elements in a tuple using indexing, similar to lists.
- Understand 0-based indexing and the slicing operator for tuples.
- Identify scenarios where tuples are useful, especially when dealing with collections of related data that should not change.
- Apply relational operators to tuples, which compare elements in a pairwise manner.
Similar to a list, a tuple is a sequence of values which can be of any type and are indexed by integers. The key difference however is that a tuple is immutable meaning their contents cannot be changed after creation. Tuples are typically used to group related data together.
Example 12
Using the example code above, predict the output for the following:
- What will be printed for the original climate info (line 3)?
- What will the weather, temperature, and humidity variables contain (lines 6, 9 and 12)?
- What will be printed for the sub-tuple (line 15)?
- What will the comparison result be (line 18)?
Copy the code into a Python environment and run the program. Were you right?
Creating Tuples
You create a tuple by enclosing a comma-separated sequence of elements within parentheses ()
.
Alternatively a tuple can be created by calling the function tuple()
:
The tuple()
function takes only one argument, so best to think of it as converting another type into a tuple type. As in the example above that takes the string "apple" and returns a tuple with the elements of that string.
Similarly, if we give tuple()
a list:
Accessing Elements
Elements in a tuple are accessed using indexing, just like in lists. Python uses 0-based indexing.
The slicing operator will also work on tuples:
But, if you try to modify any element in a tuple you will get an error:
Use Cases
Tuples are useful when you have a collection of related data that should not change. For example, coordinates (x, y), date and time (year, month, day, hour, minute), and more.
Comparing tuples
Relational operators can be applied to tuples. They start by comparing the first element of each tuple and then move to the second and so on:
Tuple assignment
There is a unique Python feature that can be used as a tuple can be on the left of an assignment statement. This is easier to show in an example than explain!
A neat use of this feature is to swap the values of two variables:
We can go further and use it, for example to split an email address into the username and domain:
Dictionaries and tuples
Recall the example for the section on dictionaries:
The output is:
If we call the items()
function on our dictionary, it returns a list of tuples as dict_items()
. Each item in the list is a tuple with key value pairs:
It helps to first convert the in-built dict_items()
form to a list:
As this is now a list of tuples, they can be sorted.
Similarly, we saw the following used when looking at dictionaries:
The key
and value
here is a tuple (without the brackets, as brackets are optional).
Tuples as return values
Another neat feature of the Python tuple is when we might want to return more than one value from a function. Consider the following example:
The function get_name_and_age()
returns a tuple containing two values: the name
and age
. The caller of the function can then unpack the tuple into separate variables or use it as-is:
Activity
Modify the example program to make the following changes:
- Attempt to change an element in the tuple. What happens?
- Create a new tuple with updated values.
- Combine tuples to form a new tuple.
- Iterate through the tuple and print each element.
Climate Quest Project
Throughout this topic we'll be working on a large scale project: Climate Quest. In this project a player embarks on a journey to combat the effects of climate change by making decisions that impact the environment. Each choice affects the outcome of the game, emphasizing the importance of individual actions in addressing climate change.
There is no additional task for tuples for the Climate Quest project. USe the time to continue the refactoring exercise from the previous task.
Questions
Programming Tasks
For each of the following tasks write a program using Python.
Write a Python program that takes a string as input and converts it into a tuple of individual characters. Then, display a slice of the tuple containing the characters from the 2nd to the 5th position.
Write a Python program that prompts the user to enter an email address and then splits it into a tuple containing the username and domain. Display both parts separately.
Create a program that stores daily temperature records as tuples. Allow the user to input the temperature for each day of a week (e.g., Monday to Sunday). Then, find and display the maximum and minimum temperatures for the week using tuple operations.