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.
Share your thoughts in the comments
Please Login to comment...