Core Tuple Operations
While tuples are immutable, you can still perform a wide range of non-modifying operations on them. These operations allow you to access data, combine tuples, and check for membership, all of which return new tuples or values without changing the original.
1. Accessing Elements: Indexing and Slicing
Like lists, tuples are ordered sequences, so you can access their elements using zero-based indexing and slicing.
Indexing
Use square brackets []
with an index number to get the element at that position. Negative indices count from the end of the tuple.
Pyground
Access the first and last elements of a tuple of weekdays.
Expected Output:
First day: Monday Last day: Friday
Output:
Immutability in Action: Attempting to change an element via its index will result in a TypeError
. This is the core difference between a tuple and a list.
my_tuple = (1, 2, 3)
my_tuple[0] = 99 # This line will raise a TypeError!
2. Combining and Repeating
You can create new tuples by concatenating or repeating existing ones.
The +
operator combines two tuples to create a new, larger tuple.
Pyground
Combine two tuples of numbers.
Expected Output:
(1, 2, 3, 4, 5, 6)
Output:
3. Membership Testing
Use the in
and not in
operators to check if an element exists within a tuple. These operations return a boolean value (True
or False
).
Pyground
Check if 'green' is in a tuple of primary colors.
Expected Output:
Is 'green' a primary color? False Is 'green' not a primary color? True
Output:
4. Iteration
You can loop over the elements of a tuple just like you would with a list.
A standard for
loop iterates through each element in the tuple from beginning to end.
Pyground
Print each item in a shopping list tuple.
Expected Output:
- apples - bananas - bread
Output:
5. Comparing Tuples
Python compares tuples lexicographically, element by element, from left to right. The comparison stops as soon as it finds a difference.
Pyground
Compare several version number tuples.
Expected Output:
(1, 2, 5) < (1, 3, 1): True (1, 2, 5) == (1, 2, 5): True (1, 3, 1) > (1, 2, 5): True
Output:
This behavior is extremely useful for sorting. You can sort a list of items based on multiple criteria by providing a key that returns a tuple. For example, key=lambda item: (item.priority, item.date)
.