Introduction:
In Python, a tuple is a type of data structure that is similar to a list, but with one key difference—tuples are immutable. This means that once a tuple is created, you cannot change, add, or remove its elements, whilst the program is running. Tuples are useful when you need to store a collection of items that should not be modified, such as coordinates or configuration settings.
Just like lists, tuples can store multiple values in a single variable, and they can contain any data type (numbers, strings, other tuples, etc.). However, because they are immutable, they provide some advantages, such as better performance when large, constant data sets are needed.
Key Difference Between Lists and Tuples:
- Lists: Mutable, meaning you can change the content (add, remove, modify elements).
- Tuples: Immutable, meaning once they are created, they cannot be modified.
Real-World Example: Imagine a tuple being like a mailing address—a fixed set of information (house number, street name, city) that shouldn't change once set. You wouldn't expect the house number to change! This is how tuples work; they store fixed sets of information.
Here’s an example of creating a tuple:
coordinates = (10, 20)
In this example, we’ve created a tuple coordinates
to store the values 10
and 20
.
Predict:
Let's take a look at this code. Can you predict what the output will be?
fruits = ("apple", "banana", "cherry") print(fruits[1])
Think about how lists and tuples work. Tuples, like lists, are zero-indexed, meaning the first element is at index 0
. What do you think will be printed when we access fruits[1]
?
Run:
Now, let’s run a simple example of creating and using tuples in Python. This example shows how a tuple can be created, and its elements accessed by index.
When you run the code, observe how the tuple is created and how each element is accessed. Notice that we use indexing just like we would with a list, but since tuples are immutable, we cannot modify the content.
Investigate:
Let's investigate how immutability works with tuples. The following example tries to modify an element of the tuple. What do you think will happen when you try to run this code?
Instructions: Run this code and observe what happens. Tuples are immutable, so trying to change an element should result in an error. Think about why this is important when you want data to remain constant in your program.
Modify:
Now it’s your turn to modify the code. Below is an incomplete program that tries to access an element from a tuple, but there’s a mistake in the code. Can you fix the code so that it correctly prints the second number in the tuple?
Hint: Remember that Python uses zero-based indexing. The first element is at index 0
, the second element is at index 1
, and so on.