Tuples
Introduction
A tuple is an immutable sequence of values:
Tuples resemble lists in that they can be indexed and sliced:
The key difference between lists and tuples is that tuples cannot be updated in-place due to their immutability. Therefore, the following operation will raise an error:
As a result, elements in a tuple cannot be appended, inserted, or deleted. The only methods defined for tuples are count and index, which function as expected:
We can iterate through a tuple using a for loop:
Since tuples are immutable, they are passed by value in functions, similar to other immutable types like strings and numbers. Useful functions for tuples include sum, max, and min.
More on Tuples
Here are some additional points about tuples:
- A singleton tuple should be defined with a comma:
If the comma is removed:
- A list can be converted into a tuple, and vice versa:
- A tuple can hold a non-homogeneous sequence of items:
- Membership can be checked using the
inkeyword:
- Tuples can be nested:
- A tuple can hold mutable objects:
Although a_tuple is immutable, the elements inside it are mutable. We can verify that the identity of the element remains unchanged:
This shows that while the values inside mutable objects can change, their identities remain the same.
Lists and Tuples Comparison
Here’s a brief summary highlighting the similarities and differences between lists and tuples:
| List | Tuple |
|---|---|
| Mutable | Immutable |
L = [1, 2, 3] |
T = (1, 2, 3) |
| Supports indexing and slicing | Supports indexing and slicing |
| Supports item assignment | Doesn't support item assignment |
Supported methods: count, index, append, insert, remove, pop, and others |
Supported methods: count, index |
To get a list: list(obj) |
To get a tuple: tuple(obj) |
The relationship between lists and tuples can be further illustrated with an example of populating a list with ordered pairs of positive integers whose product is 100:
Here, pairs is a list of tuples. Using tuples is preferable because the two elements in each pair have a well-defined relationship, and we want to avoid accidental modifications.
Packing and Unpacking
Despite seeming redundant, tuples play a significant role in Python. For example:
This is an example of tuple packing where the values 1, 2, and 3 are packed into a tuple. The reverse operation, sequence unpacking, is demonstrated as follows:
Multiple assignment combines tuple packing and sequence unpacking:
Any sequence can be unpacked:
This functionality also applies when multiple values are returned from functions:
In the return statements, the multiple values are packed into a tuple, demonstrating how functions can return tuples.