Q:

Python program to access front and rear element from tuple

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Accessing front and rear elements of tuple

In this article, we will be learning to access front and rear elements of the tuple in Python programming language using different methods.

Input:
(4, 1, 7, 8, 5, 3)

Output:
4, 3

Extracting the first and last, elements can be done easily by getting the value at index 0 and n-1. This can be done in Python using multiple ways.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to extract the elements at the first and last index is by using the bracket expression as we extract in a list.

  • The first element extracted as [0]
  • The last element extracted as [-1]
    # Python program to access front and rear 
    # elements from tuple
    
    # Initializing and printing tuple
    intTup = (4, 1, 7, 8, 5, 3)
    print("The elements tuple are " + str(intTup))
    
    # Accessing and printing front and 
    # rear elements from the tuple 
    frontEle = intTup[0] 
    rearEle = intTup[-1]
    
    print("The front element of tuple is : " + str(frontEle))
    print("The rear element of tuple is : " + str(rearEle))

Output:

The elements tuple are (4, 1, 7, 8, 5, 3)
The front element of tuple is : 4
The rear element of tuple is : 3

Method 2:

Another method to solve the problem is by using Python's itemgetter operation from the operator library. The itemgetter returns the values at the required index from the calling collection.

# Python program to access front and rear
# elements from Tuple

import operator

# Initializing and printing tuple
intTup = (4, 1, 7, 8, 5, 3)
print("The elements tuple are " + str(intTup))

# Accessing and printing front and rear 
# elements from the tuple 
frontEle = operator.itemgetter(0)(intTup)
rearEle = operator.itemgetter(-1)(intTup)

print("The front element of tuple is : " + str(frontEle))
print("The rear element of tuple is : " + str(rearEle))

Output:

The elements tuple are (4, 1, 7, 8, 5, 3)
The front element of tuple is : 4
The rear element of tuple is : 3

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to find the maximum element in tupl... >>
<< Python program to chunk tuples to N size...