Tuples are immutable sequences in Python that can store a collection of items. Often, we might need to the retrieve the first and last elements from the tuple. In this article, we'll explore how to achieve this using the various methods in Python.
Get First and Last Elements from a Tuple Using Indexing
We can use indexing to access the first and last elements of the tuple. Python indexing starts at 0 for the first element and -1 for last element.
# Create a tuple
my_tuple = (10, 20, 30, 40, 50)
# Get the first element
first_elements = my_tuple[0]
# Get the last element
last_elements = my_tuple[-1]
print("First Element:", first_elements)
print("Last Element:", last_elements)
Output :
First Element: 10
Last Element: 50Get First and Last Elements from a Tuple Using Tuple Unpacking
The Tuple unpacking allows to the assign the elements of a tuple to the individual variables. By unpacking we can easily get the first and last elements of a tuple:
# Create a tuple
my_tuple = (10, 20, 30, 40, 50)
# Unpack the tuple
first_elements, *_, last_elements = my_tuple
print("First Element:", first_elements)
print("Last Element:", last_elements)
Output :
First Element: 10
Last Element: 50Get First and Last Elements from a Tuple Using Slicing
We can also use slicing to get the first and last elements of a tuple. Slicing allows you to the specify a range of indices to the extract elements:
# Create a tuple
my_tuple = (10, 20, 30, 40, 50)
# Get the first element using the slicing
first_elements = my_tuple[:1][0]
# Get the last element using the slicing
last_elements = my_tuple[-1:]
print("First Element:", first_elements)
print("Last Element:", last_elements[0])
Output :
First Element: 10
Last Element: 50