Get 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
How toGet First and Last Elements from a Tuple in Python
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.