12.1 Index Range
The code for getting a subtuple looks just like the one for getting a sublist. In this aspect, tuples are very similar to lists. Don't want to repeat the material, but you know what they say... repetition is the mother of learning.
Getting subtuples, or slicing, allows you to extract parts of a tuple to create new tuples. This is especially handy when you need to work with specific data segments stored in a tuple.
Slicing Syntax
Slices are created using square brackets, with the start and end indices specified inside, separated by a colon. If the start index is not provided, slicing begins at the first element; if the end index is not provided, slicing goes to the end of the tuple.
You can get a slice of a tuple using the syntax tuple[start:stop:step], where:
-
start
— the start index of the element (inclusive); -
stop
— the end index of the element (exclusive); -
step
— the step with which elements are selected.
Examples:
my_tuple = (0, 1, 2, 3, 4, 5)
sub_tuple = my_tuple[1:4] # Get a subtuple with elements from index 1 to 3
print(sub_tuple) # Outputs (1, 2, 3)
sub_tuple_with_step = my_tuple[0:6:2] # Get every second element from 0 to 5
print(sub_tuple_with_step) # Outputs (0, 2, 4)
If start
is not specified, it defaults to 0; if stop
is not specified, it defaults to len(tuple)
. The step
parameter defaults to 1.
Examples:
# Create a tuple with elements from 0 to 5
my_tuple = (0, 1, 2, 3, 4, 5)
# Create a new tuple starting from the second element of the original tuple
sub_tuple = my_tuple[1:]
print(sub_tuple) # Output: (1, 2, 3, 4, 5)
# Create a new tuple including elements from the beginning to the fourth element
# (index 4) of the original tuple, with a step of 1 (default)
sub_tuple_with_step = my_tuple[:5]
print(sub_tuple_with_step) # Output: (0, 1, 2, 3, 4)
12.2 Negative Indices
Negative indices in Python start at -1, which corresponds to the last element of a list (or tuple). -2 would point to the second-to-last element, and so on. Using negative indices simplifies access to the elements from the end of a tuple without needing to calculate their position from the start.
Examples of Use
Let's consider using negative indices to form a slice. Suppose we have a tuple with values:
my_tuple = (10, 20, 30, 40, 50, 60, 70, 80)
To get a subtuple containing elements from the end to the middle of the tuple, we can use negative indices.
sub_tuple = my_tuple[-3:-1]
print(sub_tuple) # Outputs (60, 70)
Thus, my_tuple[-3:-1]
selects elements with indices -3
(third from the end) to -1
(not including the last), giving us the tuple (60, 70).
Getting the Last Element of a Tuple:
my_tuple = (10, 20, 30, 40, 50)
last_element = my_tuple[-1]
print(last_element) # Outputs 50
Here, my_tuple[-1]
will always return the last element of the tuple, which is very convenient when the exact number of elements in a tuple is unknown.
Reversing Tuple Elements:
my_tuple = (10, 20, 30, 40, 50)
reversed_tuple = my_tuple[::-1]
print(reversed_tuple) # Outputs (50, 40, 30, 20, 10)
Using the slice [::-1] allows you to easily and efficiently reverse the order of elements in a tuple, getting a new tuple with elements in reverse order.
12.3 Checking if an Element is in a Tuple
Checking if an element is in a tuple is a standard operation to find out if an element is present in a tuple.
This is done using the in
operator, which returns True if the element is present in the tuple, and False otherwise.
Using the in
Operator
The in
operator is a simple and intuitive way to check for an element:
my_tuple = (1, 2, 3, 4, 5)
element = 3
if element in my_tuple:
print(f"{element} is in the tuple.")
else:
print(f"{element} is not in the tuple.")
Checking if an Element is Absent:
If you want to make sure an element is absent from a tuple, just use the not in
construct:
names = ('Alice', 'Bob', 'Charlie')
search_name = 'Alice'
if search_name not in names:
print(f"{search_name} is not in the tuple.")
else:
print(f"{search_name} is in the tuple.")
It's almost no different from working with a list — that's the universality and simplicity of Python.
GO TO FULL VERSION