Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Access front and rear element of Python tuple
When working with Python tuples, you often need to access the first and last elements. Python provides simple indexing syntax to access these elements using [0] for the front element and [-1] for the rear element.
A tuple is an immutable data type, meaning values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important containers since they ensure read-only access.
Syntax
# Access front element front_element = tuple_name[0] # Access rear element rear_element = tuple_name[-1] # Access both together front_and_rear = (tuple_name[0], tuple_name[-1])
Example
Below is a demonstration of accessing front and rear elements of a tuple −
my_tuple_1 = (87, 90, 31, 85, 34, 56, 12, 5)
print("The first tuple is :")
print(my_tuple_1)
my_result = (my_tuple_1[0], my_tuple_1[-1])
print("The front and rear elements of the tuple are : ")
print(my_result)
The first tuple is : (87, 90, 31, 85, 34, 56, 12, 5) The front and rear elements of the tuple are : (87, 5)
Accessing Individual Elements
You can also access front and rear elements separately ?
data = (10, 20, 30, 40, 50)
front = data[0]
rear = data[-1]
print(f"Front element: {front}")
print(f"Rear element: {rear}")
print(f"Sum of front and rear: {front + rear}")
Front element: 10 Rear element: 50 Sum of front and rear: 60
How It Works
-
Positive indexing:
[0]accesses the first element -
Negative indexing:
[-1]accesses the last element from the end -
Tuple creation: Combine both elements into a new tuple using
(front, rear)syntax - Immutability: Original tuple remains unchanged during access operations
Conclusion
Use [0] and [-1] indexing to access front and rear elements of a tuple. This approach works efficiently regardless of tuple size and maintains the immutable nature of tuples.
