Access front and rear element of Python tuple

PythonServer Side ProgrammingProgramming

When it is required to access the front and rear elements of a Python tuple, the access brackets can be used.

A tuple is an immutable data type. It means, 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 contains since they ensure read-only access.

Below is a demonstration of the same −

Example

Live Demo

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)

Output

The first tuple is :
(87, 90, 31, 85, 34, 56, 12, 5)
The front and rear elements of the tuple are :
(87, 5)

Explanation

  • A tuple is defined, and is displayed on the console.
  • The first element and the last element of the tuple are accessed using indexing and negative indexing respectively.
  • This is assigned to a value.
  • It is displayed as output on the console.
raja
Published on 11-Mar-2021 09:54:27
Advertisements