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 | Remove similar element rows in tuple Matrix
Next article icon

Python – Pair elements with Rear element in Matrix Row

Last Updated : 09 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
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.



Next Article
Python | Remove similar element rows in tuple Matrix
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python | Row with Minimum element in Matrix
    We can have an application for finding the lists with the minimum value and print it. This seems quite an easy task and may also be easy to code, but sometimes we need to print the entire row containing it and having shorthands to perform the same are always helpful as this kind of problem can come
    5 min read
  • Replace index elements with elements in Other List-Python
    The task of replacing index elements with elements from another list involves mapping the indices from one list to the corresponding elements in a second list. For each index in the first list, the element at that index is retrieved from the second list and stored in a new result list. For example,
    4 min read
  • Search Elements in a Matrix - Python
    The task of searching for elements in a matrix in Python involves checking if a specific value exists within a 2D list or array. The goal is to efficiently determine whether the desired element is present in any row or column of the matrix. For example, given a matrix a = [[4, 5, 6], [10, 2, 13], [1
    3 min read
  • Python - Check Similar elements in Matrix rows
    Given a Matrix and list, the task is to write a Python program to check if all the matrix elements of the row are similar to the ith index of the List. Input : test_list = [[1, 1, 1], [4, 4], [3, 3, 3], [5, 5, 5, 5]] Output : True Explanation : All rows have same elements.Input : test_list = [[1, 1,
    8 min read
  • Python | Remove similar element rows in tuple Matrix
    Sometimes, while working with data, we can have a problem in which we need to remove elements from the tuple matrix on a condition that if all elements in row of tuple matrix is same. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + all() This ta
    6 min read
  • Python - Rows with all List elements
    Given a Matrix, get all the rows with all the list elements. Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1, 8], [6, 1, 2]], sub_list = [1, 2] Output : [[2, 1, 8], [6, 1, 2]] Explanation : Extracted lists have 1 and 2. Input : test_list = [[7, 6, 3, 2], [5, 6], [2, 1, 8], [6, 1, 2]], sub_list = [2
    8 min read
  • Python - Row-wise element Addition in Tuple Matrix
    Sometimes, while working with Python tuples, we can have a problem in which we need to perform Row-wise custom elements addition in Tuple matrix. This kind of problem can have application in data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [[('Gfg', 3
    4 min read
  • Python | Remove last element from each row in Matrix
    Sometimes, while working with Matrix data, we can have a stray element attached at rear end of each row of matrix. This can be undesired at times and wished to be removed. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + del + list slicing The combination of th
    6 min read
  • Python - Test if all rows contain any common element with other Matrix
    Given two Matrices, check if all rows contain at least one element common with the same index row of other Matrix. Input : test_list1 = [[5, 6, 1], [2, 4], [9, 3, 5]], test_list2 = [[9, 1, 2], [9, 8, 2], [3, 7, 10]] Output : True Explanation : 1, 2 and 3 are common elements in rows. Input : test_lis
    5 min read
  • Python - Dual Element row with Maximum difference
    Sometimes, while working with Python Matrix, we can have Matrix with its elements to be rows with just two elements and we may desire to get row with elements having maximum difference. This can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #
    6 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