Python – Rear element extraction from list of tuples records
Last Updated :
08 May, 2023
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
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ( "The original list is : " + str (test_list))
res = [lis[ - 1 ] for lis in test_list]
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:
- Importing the itemgetter module from the operator library.
- 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.
- Printing the original list using the print() function, which will display the list of tuples on the console.
- 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.
- Converting the output of the map() function to a list using the list() function.
- Assigning the extracted last elements to a new list named res.
- 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
from operator import itemgetter
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ( "The original list is : " + str (test_list))
res = list ( map (itemgetter( - 1 ), test_list))
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
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)
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ( "The original list is : " + str (test_list))
res = rear_element_extraction(test_list)
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)
Auxiliary Space: O(n)
Method#4:Using enumerate
Approach:
- Initialize a list of tuples test_list.
- Print the original list test_list.
- Use enumerate() to get the index and tuple of each record in test_list.
- For each tuple in test_list, iterate over its elements using range() and select the last element using its index.
- Append the selected element to a new list res.
- Print the final list res.
Below is the implementation of the above approach:
Python3
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ( "The original list is : " + str (test_list))
res = [tup[idx] for _, tup in enumerate (test_list) for idx in range ( len (tup) - 1 , len (tup))]
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(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:
- Import numpy module as np.
- Initialize a list of tuples called test_list.
- Print the original test_list.
- Convert the test_list to a numpy array using np.array().
- Extract the last column of the numpy array using numpy slicing with arr[:, -1].
- Store the extracted elements in a new list called res.
- Print the list with only the last element of each tuple.
Python3
import numpy as np
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ( "The original list is : " + str (test_list))
arr = np.array(test_list)
res = arr[:, - 1 ]
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 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:
- Initialize a list of tuples called test_list
- Print the original list using the print() function
- Create an empty list called res to store the extracted elements
- 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
- Print the result using the print() function.
Below is the implementation of the above approach:
Python3
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ( "The original list is : " + str (test_list))
res = []
for tup in test_list:
res.append(tup[ - 1 ])
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
test_list = [( 1 , 'Rash' , 21 ), ( 2 , 'Varsha' , 20 ), ( 3 , 'Kil' , 19 )]
print ( "The original list is: " + str (test_list))
res = []
for tup in test_list:
res.append(tup[ - 1 ])
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.
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
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
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 - 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
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
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 element from list succeeded by K
Given a list, extract the elements which are having K as the next element. Input : test_list = [2, 3, 5, 7, 8, 5, 3, 5], K = 3 Output : [2, 5] Explanation : Elements before 3 are 2, 5. Input : test_list = [2, 3, 5, 7, 8, 5, 3, 8], K = 8 Output : [7, 3] Explanation : Elements before 8 are 7, 3. Metho
5 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
Python program to remove last element from Tuple
Given a tuple, the task is to write a Python program to delete the last element in the tuple in Python. Example: Input: ("geeks", "for", "geeks") Output:("geeks", "for") Explanation: Here we are deleting the last element of the tuple and finally modifying the original one. Note: Tuples are immutable
3 min read