Sunday, November 17, 2024
Google search engine
HomeLanguagesPython – Rear element extraction from list of tuples records

Python – Rear element extraction from list of tuples records

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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments