Open In App

Python – Pair elements with Rear element in Matrix Row

Last Updated : 09 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with data, we can have a problem in which we need to pair each element in container to a specific index element, like rear element. This kind of problem can have application in many domains. Lets discuss certain ways in which this task can be performed. 

Method #1 : Using list comprehension This is one way in which this task can be performed. In this, we iterate through each row element in list and pair it with rear element using negative indexing of list. 

Python3




# Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using list comprehension
 
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Pair elements with Rear element in Matrix Row
# using list comprehension
res = []
for sub in test_list:
    res.append([[ele, sub[-1]] for ele in sub[:-1]])
     
# printing result
print ("The list after pairing is : " + str(res))


Output : 

The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
The list after pairing is : [[[4, 6], [5, 6]], [[2, 5], [4, 5]], [[6, 5], [7, 5]]]

  Method #2 : Using product() + loop The combination of above methods can also be used to perform this task. In this, we iterate through the list and perform task of pairing using product and hence reducing one pair of loop. 

Python3




# Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using product() + loop
from itertools import product
 
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Pair elements with Rear element in Matrix Row
# using product() + loop
res = []
for idx in test_list:
    res.append(list(product(idx[:-1], [idx[-1]])))
     
# printing result
print ("The list after pairing is : " + str(res))


Output : 

The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
The list after pairing is : [[[4, 6], [5, 6]], [[2, 5], [4, 5]], [[6, 5], [7, 5]]]

Method#3: Using zip()+loop.

Python3




#Python3 code to demonstrate
#Pair elements with Rear element in Matrix Row
#using zip function
 
#Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
 
#printing original list
print("The original list is : " + str(test_list))
 
#Pair elements with Rear element in Matrix Row
#using zip function
res = []
for sub in test_list:
    res.append(list(zip(sub[:-1], [sub[-1]] * (len(sub) - 1))))
 
#printing result
print ("The list after pairing is : " + str(res))
 
#this code contributed by tvsk


Output

The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
The list after pairing is : [[(4, 6), (5, 6)], [(2, 5), (4, 5)], [(6, 5), (7, 5)]]

Time Complexity: O(n^2)

Auxiliary Space: O(n)

Method#4: Using map() and zip_longest()

Python3




#Python3 code to demonstrate
#Pair elements with Rear element in Matrix Row
#using map() and zip_longest()
from itertools import zip_longest
 
#Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
 
#printing original list
print("The original list is : " + str(test_list))
 
#Pair elements with Rear element in Matrix Row
#using map() and zip_longest()
res = [list(map(lambda x: (x[0], sub[-1]), zip_longest(sub[:-1], [], fillvalue=sub[-1]))) for sub in test_list]
 
#printing result
print("The list after pairing is : " + str(res))


Output

The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
The list after pairing is : [[(4, 6), (5, 6)], [(2, 5), (4, 5)], [(6, 5), (7, 5)]]

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

Explanation:

Here, we are using map() function to iterate through each element of each sublist. Inside the map function, we use the lambda function to pair each element of the sublist with the last element of the same sublist. We use the zip_longest() function from the itertools module to get the elements of the sublist. We pass the sublist as the first argument, an empty list as the second argument, and the fillvalue as the last element of the sublist. This way we pair each element of the sublist with the last element. Finally, we store all the paired elements of all the sublists inside a list named “res”.

Method 5: Using nested loop

Step-by-step approach:

  • Initialize the input list of lists.
  • Print the original list.
  • Initialize an empty list to store the results.
  • For each sub-list in the input list, create a new list to store the paired elements.
  • Iterate through each element in the sub-list, except the last element.
  • For each element, pair it with the last element in the sub-list and append the pair to the new list.
  • Append the new list of paired elements to the results list.
  • Print the results list.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using nested loop
 
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Pair elements with Rear element in Matrix Row
# using nested loop
res = []
for sub in test_list:
    temp = []
    for i in range(len(sub)-1):
        temp.append([sub[i], sub[-1]])
    res.append(temp)
 
# printing result
print("The list after pairing is : " + str(res))


Output

The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
The list after pairing is : [[[4, 6], [5, 6]], [[2, 5], [4, 5]], [[6, 5], [7, 5]]]

Time complexity: O(n^2), where n is the length of the longest sub-list.
Auxiliary space: O(n^2) as we are creating a new list for each sub-list in test_list.

Method #7: Using list comprehension with tuple packing and unpacking:

This method uses list comprehension to pair each element of the row with the last element of the row using tuple packing and unpacking.

Steps:

  • Initialize an empty list res to store the result.
  • Loop through each sub-list in the given list test_list.
  • For each sub-list, create a list comprehension that packs each element of the sub-list with the last element of the sub-list into a tuple using tuple packing and unpacking.
  • Append the resulting list of tuples to res.
  • Print the original list and the resulting list.

Python3




# Python3 code to demonstrate
# Pair elements with Rear element in Matrix Row
# using list comprehension with tuple packing and unpacking
 
# Initializing list
test_list = [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Pair elements with Rear element in Matrix Row using list comprehension with tuple packing and unpacking
res = [[(ele, sub[-1]) for ele in sub[:-1]] for sub in test_list]
 
# Printing result
print("The list after pairing is : " + str(res))


Output

The original list is : [[4, 5, 6], [2, 4, 5], [6, 7, 5]]
The list after pairing is : [[(4, 6), (5, 6)], [(2, 5), (4, 5)], [(6, 5), (7, 5)]]

Time complexity: O(N*M), where N is the number of rows and M is the number of columns in the input matrix.
Auxiliary space: O(N*M), where N is the number of rows and M is the number of columns in the input matrix.



Similar Reads

Python - Rear column in Multi-sized Matrix
Given a Matrix with variable lengths rows, extract last column. Input : test_list = [[3, 4, 5], [7], [8, 4, 6], [10, 3]] Output : [5, 7, 6, 3] Explanation : Last elements of rows filtered. Input : test_list = [[3, 4, 5], [7], [8, 4, 6]] Output : [5, 7, 6] Explanation : Last elements of rows filtered. Method #1: Using loop This is brute way to solve
4 min read
Access front and rear element of Python tuple
Sometimes, while working with records, we can have a problem in which we need to access the initial and last data of a particular record. This kind of problem can have application in many domains. Let's discuss some ways in which this problem can be solved. Method #1: Using Access Brackets We can perform the possible get of front and rear element i
6 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 structure can be implemented easily using lists. Method #
6 min read
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:
8 min read
Python - Test rear digit match in all list elements
Sometimes we may face a problem in which we need to find a list if it contains numbers ending with the same digits. This particular utility has an application in day-day programming. Let’s discuss certain ways in which this task can be achieved. Method #1: Using list comprehension + map() We can approach this problem by converting the elements to t
6 min read
Python | Rear elements from Tuple Strings
Yet another peculiar problem that might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This article solves the problem of extracting only the rear index element of each string in a tuple. Let’
5 min read
Python | Retain K Front and Rear elements
Sometimes, we require to shrink a list by deletion of its certain elements. One of the methods that is employed to perform this particular task is front and rear element retention and deletion of rest elements. It is a good utility whose solution can be useful to have. Let’s discuss certain ways in which this can be performed. Method #1: Using list
8 min read
Python - Rear elements Average in List
Sometimes, while working with data, we can have a problem in which we need to perform the mean of all the rear elements that come after K. This can be an application in Mathematics and Data Science domain. Let us discuss certain ways in which this task can be performed. Method #1 : Using sum() + list comprehension The combination of the above funct
6 min read
Python - Rear Kth elements
Given a list, the task is to extract all Kth elements from rear end. Input : test_list = [3, 4, 5, 2, 1], K = 2 Output : [1, 5, 3] Explanation : Every 2nd elements are extracted from rear starting from 1. Input : test_list = [3, 4, 5], K = 1 Output : [5, 4, 3] Explanation : Every elements are extracted from rear starting from 1. Method #1 : Using l
3 min read
Python - Concatenate Rear elements in Tuple List
Given a tuple list where we need to concatenate rear elements. Input : test_list = [(1, 2, "Gfg"), ("Best", )] Output : Gfg Best Explanation : Last elements are joined. Input : test_list = [(1, 2, "Gfg")] Output : Gfg Explanation : Last elements are joined. Method #1 : Using list comprehension + join() In this, we check for last element using "-1",
6 min read
Practice Tags :