Python | Custom length Matrix
Last Updated :
02 May, 2023
Sometimes, we need to initialize a matrix in Python of variable length from the list containing elements. In this article, we will discuss the variable length method initialization and certain shorthands to do so. Let's discuss certain ways to perform this.
Method #1: Using zip() + list comprehension The zip function combined with the list comprehension can help to achieve this particular task. The zip function can help to zip the counter list with the element list and list comprehension does the work of construction of matrix.
Python3
# Python3 code to demonstrate
# Custom length Matrix
# using zip() + list comprehension
# initializing list
test_list = ['a', 'b', 'c']
# initializing counter list
counter_list = [1, 4, 2]
# printing original list
print("The original list is : " + str(test_list))
# printing counter list
print("The counter list is : " + str(counter_list))
# using zip() + list comprehension
# Custom length Matrix
res = [[i] * j for i, j in zip(test_list, counter_list)]
# printing result
print("The custom length matrix is : " + str(res))
Output : The original list is : ['a', 'b', 'c']
The counter list is : [1, 4, 2]
The custom length matrix is : [['a'], ['b', 'b', 'b', 'b'], ['c', 'c']]
Time Complexity: O(n*n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2 : Using map() + mul operator This particular problem can also be solved using the inbuilt mul operator which performs multiplication of liked index elements and map function performs the task of formation of matrix.
Python3
# Python3 code to demonstrate
# Custom length Matrix
# using map() + mul operator
from operator import mul
# initializing list
test_list = ['a', 'b', 'c']
# initializing counter list
counter_list = [1, 4, 2]
# printing original list
print("The original list is : " + str(test_list))
# printing counter list
print("The counter list is : " + str(counter_list))
# using map() + mul operator
# Custom length Matrix
res = list(map(mul, [['a'], ['b'], ['c']], counter_list))
# printing result
print("The custom length matrix is : " + str(res))
Output : The original list is : ['a', 'b', 'c']
The counter list is : [1, 4, 2]
The custom length matrix is : [['a'], ['b', 'b', 'b', 'b'], ['c', 'c']]
Method #3 : Using looping + *: Here is another approach using a for loop and the * operator:
Python3
# Initialize the lists
test_list = ['a', 'b', 'c']
counter_list = [1, 4, 2]
# Initialize the result list
result = []
# Iterate through the lists
for i, j in zip(test_list, counter_list):
# Append the element from test_list repeated j times to the result list
result.append([i] * j)
# Print the original lists
print("The original list is :", test_list)
print("The counter list is :", counter_list)
# Print the result
print("The custom length matrix is :", result)
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe original list is : ['a', 'b', 'c']
The counter list is : [1, 4, 2]
The custom length matrix is : [['a'], ['b', 'b', 'b', 'b'], ['c', 'c']]
This approach iterates through the test_list and counter_list using the zip() function, and for each element and its corresponding count, it appends a list containing the element repeated j times to the result list using the * operator.
For example, given the lists ['a', 'b', 'c'] and [1, 4, 2], the resulting list would be [['a'], ['b', 'b', 'b', 'b'], ['c', 'c']].
Method #4 : Using for loop+while loop
- Initiate a for loop and a while loop inside it, append each element of test_list to an empty list by each corresponding element of counter_list times and append this list to output list
- Display output list
Python3
# Python3 code to demonstrate
# Custom length Matrix
# initializing list
test_list = ['a', 'b', 'c']
# initializing counter list
counter_list = [1, 4, 2]
# printing original list
print ("The original list is : " + str(test_list))
# printing counter list
print ("The counter list is : " + str(counter_list))
# Custom length Matrix
res = []
for i in range(0,len(test_list)):
x=[]
j=1
while(j<=counter_list[i]):
x.append(test_list[i])
j+=1
res.append(x)
# printing result
print ("The custom length matrix is : " + str(res))
OutputThe original list is : ['a', 'b', 'c']
The counter list is : [1, 4, 2]
The custom length matrix is : [['a'], ['b', 'b', 'b', 'b'], ['c', 'c']]
Time Complexity : O(M*N) M - length of test_list N - length of counter_list
Auxiliary Space : O(M*N) M - length of test_list N - length of counter_list
Method #5: Using itertools.repeat()
In this approach, we will use the itertools.repeat() to achieve this particular task. The itertools.repeat() function is used to repeat a particular element n times, where n is specified by the counter_list.
Algorithm:
Initialize two empty lists, result and temp.
Iterate through each element in test_list.
Use itertools.repeat() to repeat the current element i in test_list j times, where j is the corresponding element in counter_list.
Convert the output of itertools.repeat() to a list using the list() function and append it to temp.
Append temp to result.
Print the original lists and the resulting matrix.
Python3
# Importing required module
import itertools
# initializing list
test_list = ['a', 'b', 'c']
# initializing counter list
counter_list = [1, 4, 2]
# printing original list
print("The original list is : " + str(test_list))
# printing counter list
print("The counter list is : " + str(counter_list))
# Initializing empty result list
result = []
# Iterate through each element in test_list
for i in test_list:
# Repeat the current element i in test_list j times, where j is the corresponding element in counter_list
temp = list(itertools.repeat(i, counter_list[test_list.index(i)]))
# Append temp to result
result.append(temp)
print("The custom length matrix is :", result)
OutputThe original list is : ['a', 'b', 'c']
The counter list is : [1, 4, 2]
The custom length matrix is : [['a'], ['b', 'b', 'b', 'b'], ['c', 'c']]
Time Complexity: O(n^2), where n is the length of the list test_list. This is because we use itertools.repeat() and the list() function to repeat each element i in test_list j times, where j is the corresponding element in counter_list, resulting in a list of length j. Thus, the overall time complexity is O(n*n).
Auxiliary Space: O(n^2), where n is the length of the list test_list. This is because we create a list of lists containing the repeated elements, with a maximum length of n, resulting in a space complexity of O(n*n).
Similar Reads
Python | Row lengths 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 lengths of rows of matrix in uneven sized matrix. Let's discuss certain ways in which this problem can be solved. Method #1 : Using max() + m
4 min read
Python - Custom Columns Matrix
Sometimes, while working with Python lists, we can have a problem in which we need to extract certain columns from Matrix and recreate it. This kind of problem can have applications in data domains as they use Matrix as a prominent input parameter. Let's discuss certain ways in which this task can b
5 min read
Python - Add custom dimension in Matrix
Sometimes, while working with Python Matrix, we can have a problem in which we need to add another dimension of custom values, this kind of problem can have problem in all kinds of domains such as day-day programming and competitive programming. Let's discuss certain ways in which this task can be p
4 min read
Python | Get Kth Column of Matrix
Sometimes, while working with Python Matrix, one can have a problem in which one needs to find the Kth column of Matrix. This is a very popular problem in Machine Learning Domain and having solution to this is useful. Let's discuss certain ways in which this problem can be solved. Method #1 : Using
6 min read
Add custom borders to matrix in Python
Given a Matrix, the task is to write a python program to print each row having custom borders. Input : test_list = [[4, 5, 6], [1, 4, 5], [6, 9, 1], [0, 3 ,1]], bord = "|" Output : | 4 5 6 | | 1 4 5 | | 6 9 1 | | 0 3 1 | Explanation : Matrix is ended using | border as required.Input : test_list = [[
5 min read
Python - Count the frequency of matrix row length
Given a Matrix, the task is to write a Python program to get the count frequency of its rows lengths. Input : test_list = [[6, 3, 1], [8, 9], [2], [10, 12, 7], [4, 11]] Output : {3: 2, 2: 2, 1: 1} Explanation : 2 lists of length 3 are present, 2 lists of size 2 and 1 of 1 length is present. Input :
5 min read
Python - Matrix creation of n*n
Matrices are fundamental structures in programming and are widely used in various domains including mathematics, machine learning, image processing, and simulations. Creating an nÃn matrix efficiently is an important step for these applications. This article will explore multiple ways to create such
3 min read
Initialize Matrix in Python
There are many ways to declare a 2 dimensional array with given number of rows and columns. Let us look at some of them and also at the small but tricky catches that accompany it. We can do it using list comprehension, concatenation feature of * operator and few other ways. Method 0: 2 list comprehe
4 min read
Summation Matrix columns - Python
The task of summing the columns of a matrix in Python involves calculating the sum of each column in a 2D list or array. For example, given the matrix a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]], the goal is to compute the sum of each column, resulting in [13, 13, 13]. Using numpy.sum()numpy.sum() is a hi
2 min read
Python Program for Identity Matrix
Introduction to Identity Matrix : The dictionary definition of an Identity Matrix is a square matrix in which all the elements of the principal or main diagonal are 1's and all other elements are zeros. In the below image, every matrix is an Identity Matrix. In linear algebra, this is sometimes call
4 min read