Q:

Python program to extract rear element from list of tuples record

belongs to collection: Python Tuple Programs

0

Example:

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

Extracting rear elements from list of tuples record

We have a list of tuples where each tuple contains some elements. We need to create a Python program to extract the last element of each tuple of the list.

Input:
[(1, 'python', 1991), (2, 'java', 1995), (3, 'C', 1972)]

Output:
1991, 1995, 1972

To find the solution to the problem, we will iterate over the array and then extract the last element of each tuple.

In Python, we can perform the task in multiple ways using one of the multiple methods that are present in the function.

All Answers

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

Method 1:

One method to solve the problem in Python is by using list comprehension using which we will iterate over the list and extract the value at index -1 for each tuple of the list and then print it.

# Python program to extract rear elements 
# from list of tuples record
  
# initializing and printing list of Tuples
tupList = [(1, 'python', 1991), (2, 'java', 1995), (3, 'C', 1972)]

print ("The elements of list of tuples are " + str(tupList))
  
# extracting rear elements from the list of tuples
rearElementList = [tup[-1] for tup in tupList]
      
# printing result
print ("All rear elements of list of tuples are " + str(rearElementList))

Output:

The elements of list of tuples are [(1, 'python', 1991), (2, 'java', 1995), (3, 'C', 1972)]
All rear elements of list of tuples are [1991, 1995, 1972]

Method 2:

Another method to solve the problem is by using the map() method. And map all the last values of each tuple list which are extracted using the itemgetter() method.

# Python program to extract rear elements 
# from list of tuples record
  
# initializing and printing list of Tuples
tupList = [(1, 'python', 1991), (2, 'java', 1995), (3, 'C', 1972)]

print ("The elements of list of tuples are " + str(tupList))
  
# extracting rear elements from the list of tuples
rearElementList = [tup[-1] for tup in tupList]
      
# printing result
print ("All rear elements of list of tuples are " + str(rearElementList))

Output:

The elements of list of tuples are [(1, 'python', 1991), (2, 'java', 1995), (3, 'C', 1972)]
All rear elements of list of tuples are [1991, 1995, 1972]

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 modulo of tuple element... >>
<< Python program to find the index of minimum value ...