The Wayback Machine - https://web.archive.org/web/20240808193351/https://www.geeksforgeeks.org/python-program-to-construct-nm-matrix-from-list/
Open In App

Python Program to Construct n*m Matrix from List

Last Updated : 02 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Given a list, the task is to write a python program that can construct n*m matrix.

Input : test_list = [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3], n, m = 3, 5 
Output : “Matrix Not Possible” 
Explanation : List has 12 elements and 3*5 is 15, hence Matrix not possible.

Input : test_list = [6, 3, 7, 2, 6, 8], n, m = 2, 3 
Output : [[6, 3, 7], [2, 6, 8]] 
Explanation : List converted to 2*3 matrix. 
 

Method : Using nested loop 

The constraint of n*m restricts size of list to be strictly n*m. Post achieving that, we can assign the appropriate rows and columns using nested loops.

Example 1:

Python3




# Python3 code to demonstrate working of
# Construct n*m Matrix from List
# Using loop
 
# initializing list
test_list = [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing n, m
n, m = 3, 4
 
k = 0
res = []
if n*m != len(test_list):
 
    # checking if Matrix Possible
    res = "Matrix Not Possible"
else:
 
    # Constructing Matrix
    for idx in range(0, n):
        sub = []
        for jdx in range(0, m):
            sub.append(test_list[k])
            k += 1
        res.append(sub)
 
# printing result
print("Constructed Matrix : " + str(res))


Output:

The original list is : [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3]

Constructed Matrix : [[6, 3, 7, 2], [6, 8, 4, 3], [9, 2, 1, 3]]

Time Complexity: O(n*m)
Auxiliary Space: O(n*m)

Example 2 : 

Python3




# Python3 code to demonstrate working of
# Construct n*m Matrix from List
# Using loop
 
# initializing list
test_list = [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing n, m
n, m = 5, 4
 
k = 0
res = []
 
# n*m == 20 > length, hence result not possible.
if n*m != len(test_list):
 
    # checking if Matrix Possible
    res = "Matrix Not Possible"
else:
 
    # Constructing Matrix
    for idx in range(0, n):
        sub = []
        for jdx in range(0, m):
            sub.append(test_list[k])
            k += 1
        res.append(sub)
 
# printing result
print("Constructed Matrix : " + str(res))


Output:

The original list is : [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3]

Constructed Matrix : Matrix Not Possible

Time Complexity: O(n*m)
Auxiliary Space: O(n*m)

Approach#3: Using zip()

In this approach, the zip() function is used to group the list elements into rows of length m, and the resulting tuples are converted to lists using a list comprehension. The * operator is used to unpack the list into individual arguments, and the iter() function is used to create an iterator over the list to be able to group it into rows of length m. Finally, the list() function is used to convert the tuples to lists.

Algorithm

1. Check if the given list input can be converted to an n x m matrix or not.
2. If possible, create the matrix using the zip() function to group the list elements into rows of length m.
3. Convert the resulting tuples to lists and print the matrix.

Python3




test_list = [6, 3, 7, 2, 6, 8]
n, m = 2, 3
 
if n*m != len(test_list):
    print("Matrix Not Possible")
else:
    matrix = [list(row) for row in zip(*[iter(test_list)]*m)]
    print(matrix)


Output

[[6, 3, 7], [2, 6, 8]]

Time Complexity: O(n), where n is the number of elements in the input list. The iter() function and the zip() function both iterate over the list only once, and the list comprehension iterates over the resulting tuples once as well.

Space Complexity: O(n), where n is the number of elements in the input list. The space complexity is dominated by the resulting matrix, which has n elements.

Approach#4: Using numpy:

1. Initialize list of elements.
2. Initialize n and m.
3. Create a NumPy array from the list of elements.
4. Reshape the NumPy array to have n rows and m columns.
5. Print the resulting matrix.
 

Python3




import numpy as np
 
# initializing list
test_list = [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing n, m
n, m = 3, 4
 
# Creating NumPy array
arr = np.array(test_list)
 
# Reshaping array to n x m matrix
res = arr.reshape(n, m)
 
# printing result
print("Constructed Matrix : \n" + str(res))
#This code is contributed by Rayudu.


Output:
The original list is : [6, 3, 7, 2, 6, 8, 4, 3, 9, 2, 1, 3]
Constructed Matrix : 
[[6 3 7 2]
[6 8 4 3]
[9 2 1 3]]

Time Complexity:
The time complexity is O(N), where N is the total number of elements in the input list. This is because we need to create a NumPy array and then reshape it, both of which take linear time with respect to the number of elements.

Auxiliary Space:
The space complexity is O(N), where N is the total number of elements in the input list. This is because we create a NumPy array that has the same number of elements as the input list, and the reshaping operation does not increase the total amount of space used.



Similar Reads

Python | Construct N Range Equilength String list
Sometimes, while working with Python, we can have a problem in which we need to construct a string list which contains N range numbers. But we have requirement in which we need to keep each element of equal length. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension + zfill() The combination of above
5 min read
Python - Construct variables of list elements
Sometimes, while working with python lists, we can have a problem in which we need to convert each element in list to variables and the corresponding list as the value. This can have applications in many domains such as web development and day-day programming. Let's discuss certain ways in which this task can be performed. Method #1: Using dict() +
6 min read
Python - Construct Grades List
Given a number, construct a list having all the possible Grades combination for the first N characters. Input : num = 3 Output : ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-'] Explanation : All grades till C rendered in list.Input : num = 5 Output : ['A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'E+', 'E', 'E-'] Explanati
4 min read
Python | Construct Cartesian Product Tuple list
Sometimes, while working with data, we need to create data as all possible pairs of containers. This type of application comes from the web development domain. Let's discuss certain ways in which this task can be performed. Using list comprehension list comprehension in Python is a one-liner way to perform this particular task. In this, we just sho
6 min read
Python program to construct Equidigit tuples
Given the Elements list, divide the tuple list into similar digit tuples pairs. Input : test_list = [5654, 223, 982143, 34, 1021] Output : [(56, 54), (2, 23), (982, 143), (3, 4), (10, 21)] Explanation : Element in tuples equidistributed. Input : test_list = [5654, 223, 1021] Output : [(56, 54), (2, 23), (10, 21)] Explanation : Element in tuples equ
3 min read
Python Program to Construct dictionary using random values
Given List, our task is to write a Python program to construct a dictionary with values randomly selected from range. Examples: Input : test_list = ["Gfg", "is", "Best"], i, j = 2, 9 Output : {'Gfg': 3, 'is': 9, 'Best': 4} Explanation : Random values assigned between 2 and 9. Input : test_list = ["Gfg", "is", "Best"], i, j = 2, 10 Output : {'Gfg':
4 min read
Python program to Convert a Matrix to Sparse Matrix
Given a matrix with most of its elements as 0, we need to convert this matrix into a sparse matrix in Python. Example: Input: Matrix: 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 5 0 0 0 Output: Sparse Matrix: 0 0 1 1 1 2 2 2 3 3 3 4 4 0 5 Explanation: Here the Matrix is represented using a 2D list and the Sparse Matrix is represented in the form Row Column Val
3 min read
Python Program to Convert String Matrix Representation to Matrix
Given a String with matrix representation, the task here is to write a python program that converts it to a matrix. Input : test_str = "[gfg,is],[best,for],[all,geeks]"Output : [['gfg', 'is'], ['best', 'for'], ['all', 'geeks']]Explanation : Required String Matrix is converted to Matrix with list as data type. Input : test_str = "[gfg,is],[for],[all
4 min read
Program to construct a DFA which accepts the language having all 'a' before all 'b'
Given a string S, the task is to design a Deterministic Finite Automata (DFA) for accepting the language L = {aNbM | N ≥ 0, M ≥ 0, N+M ≥ 1}. , i.e., a regular language L such that all 'a' occur before the first occurrence of 'b' {a, ab, aab, bb..., }. If the given string follows the given language L, then print “Accepted”. Otherwise, print “Not Acc
8 min read
Python | Construct string from character frequency tuple
Sometimes, while working with data, we can have a problem in which we need to perform construction of string in a way that we have a list of tuple having character and it's corresponding frequency and we require to construct a new string from that. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This is brute
5 min read
Practice Tags :
three90RightbarBannerImg