The Wayback Machine - https://web.archive.org/web/20240927132243/https://www.geeksforgeeks.org/python-assigning-subsequent-rows-to-matrix-first-row-elements/
Open In App

Python – Assigning Subsequent Rows to Matrix first row elements

Last Updated : 14 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a (N + 1) * N Matrix, assign each column of 1st row of matrix, the subsequent row of Matrix.

Input : test_list = [[5, 8, 10], [2, 0, 9], [5, 4, 2], [2, 3, 9]] Output : {5: [2, 0, 9], 8: [5, 4, 2], 10: [2, 3, 9]} 
Explanation : 5 paired with 2nd row, 8 with 3rd and 10 with 4th 
Input : test_list = [[5, 8], [2, 0], [5, 4]] Output : {5: [2, 0], 8: [5, 4]} 
Explanation : 5 paired with 2nd row, 8 with 3rd.

Method #1: Using dictionary comprehension

This is one of the ways in which this task can be performed. In this, we iterate for rows and corresponding columns using loop and assign value list accordingly in a one-liner way using dictionary comprehension.

Python3




# Python3 code to demonstrate working of
# Assigning Subsequent Rows to Matrix first row elements
# Using dictionary comprehension
 
# initializing list
test_list = [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
 
# printing original list
print("The original list : " + str(test_list))
 
# pairing each 1st col with next rows in Matrix
res = {test_list[0][ele] :  test_list[ele + 1] for ele in range(len(test_list) - 1)}
 
# printing result
print("The Assigned Matrix : " + str(res))


Output

The original list : [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
The Assigned Matrix : {5: [2, 0, 9], 8: [5, 4, 2], 9: [2, 3, 9]}

Time complexity: O(m*n), because it performs the same number of iterations as the original code.
Auxiliary space: O(m*n) as well, because it creates a dictionary with m * n keys and a list of m * n elements

Method #2 : Using zip() + list slicing + dict()

This is yet another way in which this task can be performed. In this, we slice elements to be first row and subsequent rows using list slicing and zip() performs the task of required grouping. Returned 

Python3




# Python3 code to demonstrate working of
# Assigning Subsequent Rows to Matrix first row elements
# Using zip() + list slicing + dict()
 
# initializing list
test_list = [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
 
# printing original list
print("The original list : " + str(test_list))
 
# dict() to convert back to dict type
# slicing and pairing using zip() and list slicing
res = dict(zip(test_list[0], test_list[1:]))
 
# printing result
print("The Assigned Matrix : " + str(res))


Output

The original list : [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
The Assigned Matrix : {5: [2, 0, 9], 8: [5, 4, 2], 9: [2, 3, 9]}

Method #3 : Using for loop and slicing

Python3




# Python3 code to demonstrate working of
# Assigning Subsequent Rows to Matrix first row elements
 
# initializing list
test_list = [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
 
# printing original list
print("The original list : " + str(test_list))
 
# pairing each 1st col with next rows in Matrix
a=test_list[0]
b=test_list[1:len(test_list)]
d=dict()
for i in range(0,len(a)):
    d[a[i]]=b[i]
     
 
# printing result
print("The Assigned Matrix : " + str(d))


Output

The original list : [[5, 8, 9], [2, 0, 9], [5, 4, 2], [2, 3, 9]]
The Assigned Matrix : {5: [2, 0, 9], 8: [5, 4, 2], 9: [2, 3, 9]}


Previous Article
Next Article

Similar Reads

Python - Assigning Key values to list elements from Value list Dictionary
Given a List of elements, map them with keys of matching values from a value list. Input : test_list = [4, 6, 3, 5, 3], test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4]} Output : ['is', 'Gfg', 'Gfg', 'Gfg', 'Gfg'] Explanation : 4 is present in "is" key, hence mapped in new list. Input : test_list = [6, 3, 5, 3], test_dict = {"Gfg" : [5, 3, 6], "is" :
7 min read
Python Program to Interchange elements of first and last rows in matrix
Given a 4 x 4 matrix, we have to interchange the elements of first and last row and show the resulting matrix. Examples : Input : 3 4 5 0 2 6 1 2 2 7 1 2 2 1 1 2 Output : 2 1 1 2 2 6 1 2 2 7 1 2 3 4 5 0 Input : 9 7 5 1 2 3 4 1 5 6 6 5 1 2 3 1 Output : 1 2 3 1 2 3 4 1 5 6 6 5 9 7 5 1 Method 1:The approach is very simple, we can simply swap the eleme
4 min read
Assigning multiple variables in one line in Python
A variable is a segment of memory with a unique name used to hold data that will later be processed. Although each programming language has a different mechanism for declaring variables, the name and the data that will be assigned to each variable are always the same. They are capable of storing values of data types. The assignment operator(=) assi
2 min read
Create integer variable by assigning binary value in Python
Given a binary value and our task is to create integer variables and assign values in binary format. To assign value in binary format to a variable, we use the 0b suffix. It tells the compiler that the value (suffixed with 0b) is a binary value and assigns it to the variable. Input: Var = 0b1010 Output: 10 Input: Var = 0b11001 Output: 25 Note: To p
2 min read
PyQt5 QCalendarWidget - Assigning Base Size value
In this article, we will see how we can set the base size value to the QCalendarWidget. By default base size has a value zero for both width and height, base size is used to calculate a proper calendar size if the calendar defines sizeIncrement i.e its size change when window size changes. Base size is the initial size of the calendar. In order to
1 min read
PyQt5 QCommandLinkButton - Assigning Object Name
In this article we will see how we can set the object name of the QCommandLinkButton. Object name is given for searching the specific button inside the window programmatically, also object name can be used for setting stylesheet using object name. By default developer has not set any object name to the command link although we can set it any time.
1 min read
PyQt5 QCommandLinkButton - Assigning Cursor
In this article we will see how we can set i.e assign cursor to the QCommandLinkButton. Assigning cursor means the mouse cursor will assume the new shape when it's over the command link button. Cursor shape is basically cursor icons these are used to classify the actions. In order to do this we use setCursor method with the command link button obje
1 min read
PyQt5 QDateEdit - Assigning Description
In this article we will see how we can assign a description to the QDateEdit. Description property holds the date edit's description as seen by assistive technologies. The accessible description of a date edit should convey what date edit does. While the accessible name should be a short and concise string (e.g. Office Date), the description should
2 min read
PyQt5 QDateEdit - Assigning Name Property
In this article we will see how we can assign name to the QDateEdit. Name property holds the date edit's name as seen by assistive technologies. This is the primary name by which assistive technology such as screen readers announce the given date edit. In order to do this we use setAccessibleName method with the QDateEdit object Syntax : date.setAc
1 min read
MoviePy – Assigning Audio Clip to Video File
In this article we will see how we can add external audio to the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. An audio file format is a file format for stori
2 min read
Assigning Values to Variables
In this article, we will learn how to assign values to variables in Python and other languages also. Assigning Values to Variables in PythonBelow are the steps and methods by which we can assign values to variables in Python and other languages: Direct Initialization MethodUsing Conditional OperatorAssign Values to Variables Direct Initialisation M
4 min read
Python Program to Sort Matrix Rows by summation of consecutive difference of elements
Given a Matrix, the following article depicts how to sort rows of a matrix on the basis of summation of difference between consecutive elements of a row. Input : test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]], Output : [[4, 3, 2, 1], [7, 2, 4, 5], [1, 5, 3, 6], [6, 9, 3, 2]] Explanation : 4 < 8 < 9 < 10 is consecutive
7 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, 4], [4, 4], [3, 3, 3], [5, 5, 5, 5]] Output : Fal
8 min read
Python Program to Extract Rows of a matrix with Even frequency Elements
Given a Matrix, the task is to write a Python program to extract all the rows which have even frequencies of elements. Examples: Input: [[4, 5, 5, 2], [4, 4, 4, 4, 2, 2], [6, 5, 6, 5], [1, 2, 3, 4]] Output: [[4, 4, 4, 4, 2, 2], [6, 5, 6, 5]]Explanation: frequency of 4-> 4 which is even frequency of 2-> 2 which is even frequency of 6-> 2 wh
5 min read
Python - Pair elements with Rear element in Matrix Row
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
7 min read
heapq in Python to print all elements in sorted order from row and column wise sorted matrix
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order. Examples: Input : mat= [[10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]] Output : Elements of matrix in sorted order [10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 39, 40, 45, 48, 50] This problem h
2 min read
How to Apply a Custom Function in Polars that Does the Processing Row by Row?
Polars is a fast DataFrame library in Rust and Python, designed to handle large datasets efficiently. It provides a powerful API for data manipulation, similar to pandas, but with performance optimizations that can significantly speed up your data processing tasks. One common task in data processing is applying custom functions to manipulate data r
5 min read
Select first or last N rows in a Dataframe using head() and tail() method in Python-Pandas
Let’s discuss how to select top or bottom N number of rows from a Dataframe using head() & tail() methods. 1) Select first N Rows from a Dataframe using head() method of Pandas DataFrame : Pandas head() method is used to return top n (5 by default) rows of a data frame or series Syntax: Dataframe.head(n). Parameters: (optional) n is integer value,
2 min read
How to Find the First Empty Row of an Excel File in Python
When working with data in Excel files, one common task is to find the first empty row where new data can be added. Whether you're automating a data entry process or performing data analysis, Python offers several methods to accomplish this task efficiently. In this article, we'll explore different approaches to finding the first empty row of an Exc
2 min read
Python | Print unique rows in a given boolean matrix using Set with tuples
Given a binary matrix, print all unique rows of the given matrix. Order of row printing doesn't matter. Examples: Input: mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] Output: (1, 1, 1, 0, 0) (0, 1, 0, 0, 1) (1, 0, 1, 1, 0) We have existing solution for this problem please refer link. We can solve this problem in python
2 min read
Python Counter| Find duplicate rows in a binary matrix
Given a binary matrix whose elements are only 0 and 1, we need to print the rows which are duplicate of rows which are already present in the matrix. Examples: Input : [[1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [1, 0, 1, 1, 0, 0], [1, 1, 0, 1, 0, 1], [0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 1]] Output : (1, 1, 0, 1, 0, 1) (0, 0, 1, 0, 0, 1) We have existi
2 min read
Python - Filter immutable rows representing Dictionary Keys from Matrix
Given Matrix, extract all the rows which has elements which have all elements which can be represented as dictionary key, i.e immutable. Input : test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5:4}, 3, "good"], [True, "best"]] Output : [['gfg', 1, (4, 4)], [True, 'best']] Explanation : All elements in tuples are immutable. Input : test_list =
7 min read
Python program to sort matrix based upon sum of rows
Given a Matrix, perform sort based upon the sum of rows. Input : test_list = [[4, 5], [2, 5, 7], [2, 1], [4, 6, 1]] Output : [[2, 1], [4, 5], [4, 6, 1], [2, 5, 7]] Explanation : 3 < 9 < 11 < 14. Sorted sum. Input : test_list = [[4, 5], [2, 5, 7], [4, 6, 1]] Output : [[4, 5], [4, 6, 1], [2, 5, 7]] Explanation : 9 < 11 < 14. Sorted sum
6 min read
Python Program to sort rows of a matrix by custom element count
Given Matrix, the following program shows how to sort rows of a matrix by the count of presence of numbers from a specified list. Input : test_list = [[4, 5, 1, 7], [6, 5], [9, 8, 2], [7, 1]], cus_list = [4, 5, 7] Output : [[9, 8, 2], [6, 5], [7, 1], [4, 5, 1, 7]] Explanation : 0 < 1 = 1 < 3 is order of custom elements count.Input : test_list
5 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 task can be performed using combination of above fun
6 min read
Python - Concatenate string rows in Matrix
The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the concatenation of rows of matrix in uneven sized matrix. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using join() + list comprehension The combination of above
3 min read
Python - Remove Similar Rows from Tuple Matrix
Sometimes, while working with Tuple Matrix, we can have a problem in which we get lots of data, which are similar, i.e elements are same in rows, just the ordering of tuples is different, it's sometimes, desired to get them removed. This kind of problem can have application in domains such as web development and day-day programming. Let's discuss c
9 min read
Python - Flag None Element Rows in Matrix
Given a Matrix, return True for rows which contain a None Value, else return False. Input : test_list = [[2, 4, None, 3], [3, 4, 1, None], [2, 4, 7, 4], [2, 8, None]] Output : [True, True, False, True] Explanation : 1, 2 and 4th index contain None occurrence. Input : test_list = [[2, 4, None, 3], [3, 4, 1, None], [2, 4, None, 4], [2, 8, None]] Outp
4 min read
Python program to remove rows with duplicate element in Matrix
Given Matrix, remove all rows which have duplicate elements in them. Input : test_list = [[4, 3, 2], [7, 6, 7], [2, 4, 4], [8, 9, 9]] Output : [[4, 3, 2]] Explanation : [4, 3, 2] is the only unique row. Input : test_list = [[4, 3, 3, 2], [7, 6, 7], [2, 4, 4], [8, 9, 9]] Output : [] Explanation : No unique row. Method 1 : Using list comprehension +
5 min read
Python - Rows with K string in Matrix
Given a matrix, extract row numbers with particular string occurrences. Input : test_list = [["GFG", "best", "geeks"], ["geeks", "rock"], ["GFG", "for", "CS"], ["Keep", "learning"]], K = "GFG" Output : [0, 2] Explanation : 0th index and 2nd index have "GFG" in them as element. Input : test_list = [["GFG", "best", "geeks"], ["geeks", "rock", "GFG"],
6 min read