Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Extract Elements from Ranges in List
Next article icon

Python - Rear element extraction from list of tuples records

Last Updated : 08 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print specific information from the tuple like rear index. For instance, a piece of code would want just names to be printed on all the student data. Let's discuss certain ways in which one can achieve solutions to this problem. 

Method #1: Using list comprehension 

List comprehension is the simplest way in which this problem can be solved. We can just iterate over only the rear index value in all the index and store it in a list and print it after that. 

Python3
# Python3 code to demonstrate # Rear element extraction from Records # using list comprehension  # Initializing list of tuples test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]  # Printing original list print("The original list is : " + str(test_list))  # Rear element extraction from Records # using list comprehension to get names res = [lis[-1] for lis in test_list]  # Printing result print("List with only rear tuple element : " + str(res)) 
Output : 
The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)] List with only rear tuple element : [21, 20, 19]

Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(n), as we are creating a new list to store the extracted elements.

Method #2: Using map() + itemgetter()

map() coupled with itemgetter() can perform this task in simpler way. map() maps all the element we access using itemgetter() and returns the result. 

Follow the below steps to implement the above idea:

  1. Importing the itemgetter module from the operator library.
  2. Initializing a list of tuples test_list that contains three tuples, where each tuple represents a record containing three elements: an integer value, a string value, and another integer value.
  3. Printing the original list using the print() function, which will display the list of tuples on the console.
  4. Using the map() function with the itemgetter() function to extract the last element of each tuple in the test_list. The itemgetter(-1) function is used as a key function to extract the last element of each tuple.
  5. Converting the output of the map() function to a list using the list() function.
  6. Assigning the extracted last elements to a new list named res.
  7. Printing the res list, which contains only the last element of each tuple in the test_list. This will display the extracted last elements of each tuple on the console.

Below is the implementation of the above approach: 

Python3
# Python3 code to demonstrate # Rear element extraction from Records # using map() + itergetter() from operator import itemgetter  # Initializing list of tuples test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]  # Printing original list print("The original list is : " + str(test_list))  # Rear element extraction from Records # using map() + itergetter() to get names res = list(map(itemgetter(-1), test_list))  # Printing result print("List with only rear tuple element : " + str(res)) 
Output : 
The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)] List with only rear tuple element : [21, 20, 19]

Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n), where n is the length of the input list test_list. 

Method#3: Using the Recursive method.

Python3
# Python3 code to demonstrate # Rear element extraction from Records # using recursive method   def rear_element_extraction(test_list, res=[]):     if not test_list:         return res     res.append(test_list[0][-1])     return rear_element_extraction(test_list[1:], res)   # Initializing list of tuples test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]  # Printing original list print("The original list is : " + str(test_list))  # Rear element extraction from Records using recursive function res = rear_element_extraction(test_list)  # printing result print("List with only rear tuple element : " + str(res))  # this code contributed by tvsk 

Output
The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)] List with only rear tuple element : [21, 20, 19]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method#4:Using enumerate

Approach:

  1. Initialize a list of tuples test_list.
  2. Print the original list test_list.
  3. Use enumerate() to get the index and tuple of each record in test_list.
  4. For each tuple in test_list, iterate over its elements using range() and select the last element using its index.
  5. Append the selected element to a new list res.
  6. Print the final list res.

Below is the implementation of the above approach:

Python3
# Python3 code to demonstrate  # Rear element extraction from Records # using enumerate()   # initializing list of tuples test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]  # printing original list  print ("The original list is : " + str(test_list))  # using enumerate() to get names # Rear element extraction from Records res = [tup[idx] for _, tup in enumerate(test_list) for idx in range(len(tup)-1, len(tup))]  # printing result print ("List with only rear tuple element : " + str(res)) #This code is contributed by Vinay Pinjala. 

Output
The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)] List with only rear tuple element : [21, 20, 19]

Time complexity: O(nm), where n is the number of tuples in test_list and m is the length of the longest tuple. The enumerate() function and two nested loops iterate over all the elements in each tuple, so their time complexity is proportional to m. Therefore, the overall time complexity is O(nm).

Auxiliary space: O(n), where n is the number of tuples in test_list. The res list stores only the last element of each tuple, so its size is proportional to n. Therefore, the space complexity is O(n).

Method#5:Using numpy(): 

Algorithm:

  1. Import numpy module as np.
  2. Initialize a list of tuples called test_list.
  3. Print the original test_list.
  4. Convert the test_list to a numpy array using np.array().
  5. Extract the last column of the numpy array using numpy slicing with arr[:, -1].
  6. Store the extracted elements in a new list called res.
  7. Print the list with only the last element of each tuple.
Python3
import numpy as np  # Initializing list of tuples test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]  # Printing original list print("The original list is : " + str(test_list))  # Converting list of tuples to numpy array arr = np.array(test_list)  # Extracting the last column using numpy slicing res = arr[:, -1]  # Printing result print("List with only rear tuple element : " + str(res))  # This code is contributed by Jyothi pinjala 

Output: 

The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)] List with only rear tuple element : ['21' '20' '19']

Time complexity:  O(n), where n is the number of tuples in the input list. The numpy array conversion takes O(n) time, and slicing takes constant time.
Space complexity:  O(n), where n is the number of tuples in the input list. This is because the input list is converted to a numpy array which takes O(n) space, and the resulting array containing only the last elements of each tuple also takes O(n) space.

Method #6: Using a for loop

Step-by-step approach:

  1. Initialize a list of tuples called test_list
  2. Print the original list using the print() function
  3. Create an empty list called res to store the extracted elements
  4. Use a for loop to iterate over each tuple in test_list
    • Extract the last element (which has index -1) and append it to res
  5. Print the result using the print() function.

Below is the implementation of the above approach:

Python3
# Python3 code to demonstrate  # Rear element extraction from Records # using a for loop  # Initializing list of tuples test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]  # Printing original list print("The original list is : " + str(test_list))  # using a for loop to get names res = [] for tup in test_list:     res.append(tup[-1])  # Printing result print("List with only rear tuple element : " + str(res)) 

Output
The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)] List with only rear tuple element : [21, 20, 19]

Time complexity: O(n), where n is the length of test_list because we iterate over each element in the list once.
Auxiliary space: O(n), where n is the length of test_list because we create a new list called res with n elements.

Method 6: Using Loops 

Python3
# Python3 code to demonstrate # Rear element extraction from Records # using for loop  # initializing list of tuples test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]  # printing original list print("The original list is: " + str(test_list))  # Rear element extraction from Records using for loop res = [] for tup in test_list:     res.append(tup[-1])  # printing result print("List with only rear tuple element: " + str(res)) 

Output
The original list is: [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)] List with only rear tuple element: [21, 20, 19]

Time complexity: O(n) where n is the length of the input list
Auxiliary space: O(n) where n is the length of the input list, for the output list.


Next Article
Python - Extract Elements from Ranges in List
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python tuple-programs
Practice Tags :
  • python

Similar Reads

  • Python - Extract records if Kth elements not in List
    Given list of tuples, task is to extract all the tuples where Kth index elements are not present in argument list. Input : test_list = [(5, 3), (7, 4), (1, 3), (7, 8), (0, 6)], arg_list = [6, 8, 8], K = 1 Output : [(5, 3), (7, 4), (1, 3)] Explanation : All the elements which have either 6 or 8 at 1s
    4 min read
  • Python - Extract Elements from Ranges in List
    We are given a list and list containing tuples we need to extract element from ranges in tuples list. For example, n = [10, 20, 30, 40, 50, 60, 70, 80, 90] and r = [(1, 3), (5, 7)] (ranges) we need to extract elements so that output should be [[20, 30, 40], [60, 70, 80]]. Using List ComprehensionLis
    3 min read
  • Python - Remove rear element from list
    A stack data structure is a very well-known data structure, lists in Python usually append the elements to the end of the list. For implementing a stack data structure, it is essential to be able to remove the end element from a list. Let’s discuss the ways to achieve this so that stack data structu
    6 min read
  • Python - Extracting Priority Elements in Tuple List
    Sometimes, while working with Python Records, we can have a problem in which we need to perform extraction of all the priority elements from records, which usually occur as one of the binary element tuple. This kind of problem can have possible application in web development and gaming domains. Let'
    5 min read
  • Get first element from a List of tuples - Python
    The goal here is to extract the first element from each tuple in a list of tuples. For example, given a list [(1, 'sravan'), (2, 'ojaswi'), (3, 'bobby')], we want to retrieve [1, 2, 3], which represents the first element of each tuple. There are several ways to achieve this, each varying in terms of
    2 min read
  • Python - Extract tuple supersets from List
    Sometimes, while working with Python tuples, we can have a problem in which we need to extract all the tuples, which have all the elements in target tuple. This problem can have application in domains such as web development. Let's discuss certain way in which this problem can be solved. Input : tes
    5 min read
  • Swap tuple elements in list of tuples - Python
    The task of swapping tuple elements in a list of tuples in Python involves exchanging the positions of elements within each tuple while maintaining the list structure. Given a list of tuples, the goal is to swap the first and second elements in every tuple. For example, with a = [(3, 4), (6, 5), (7,
    3 min read
  • Python - Extract Kth element of every Nth tuple in List
    Given list of tuples, extract Kth column element of every Nth tuple. Input :test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8), (6, 4, 7), (2, 5, 7), (1, 9, 10), (3, 5, 7)], K = 2, N = 3 Output : [3, 8, 10] Explanation : From 0th, 3rd, and 6th tuple, 2nd elements are 3, 8, 10. Input :test_list
    8 min read
  • Python - Extract tuples with elements in Range
    Given list of tuples, extract tuples having elements in range. Input : test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)], strt, end = 5, 6 Output : [(5, 6)] Explanation : Only 1 tuple lies in range of 5-6. Input : test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)], strt, end = 1, 10 Output :
    4 min read
  • Extract Elements from a Python List
    When working with lists in Python, we often need to extract specific elements. The easiest way to extract an element from a list is by using its index. Python uses zero-based indexing, meaning the first element is at index 0. [GFGTABS] Python x = [10, 20, 30, 40, 50] # Extracts the last element a =
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences