Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Custom length Matrix in Python
Sometimes when creating a matrix using Python, we may need to control how many times a given element is repeated in the resulting matrix. In this article, we will see how to create a matrix with a required number of elements when the elements are given as a list.
Using zip() and List Comprehension
We declare a list with elements to be used in the matrix. Then we declare another list which will hold the number of occurrences of the element in the matrix. Using the zip() function with list comprehension, we can create the resulting matrix ?
Example
elements = ['m', 'n', 'p', 'q']
# Count of elements
elem_count = [1, 0, 3, 2]
# Given Lists
print("Given List of elements:", elements)
print("Count of elements:", elem_count)
# Creating Matrix
matrix = [[x] * y for x, y in zip(elements, elem_count)]
# Result
print("The new matrix is:", matrix)
Given List of elements: ['m', 'n', 'p', 'q'] Count of elements: [1, 0, 3, 2] The new matrix is: [['m'], [], ['p', 'p', 'p'], ['q', 'q']]
Using map() with operator.mul
In this approach, we use the mul method from the operator module. The map() function applies the multiplication operation to every element pair, creating repeated strings instead of lists ?
Example
from operator import mul
elements = ['m', 'n', 'p', 'q']
# Count of elements
elem_count = [1, 0, 3, 2]
# Given Lists
print("Given List of elements:", elements)
print("Count of elements:", elem_count)
# Creating Matrix (as repeated strings)
matrix = list(map(mul, elements, elem_count))
# Result
print("The new matrix is:", matrix)
Given List of elements: ['m', 'n', 'p', 'q'] Count of elements: [1, 0, 3, 2] The new matrix is: ['m', '', 'ppp', 'qq']
Comparison
| Method | Output Type | Best For |
|---|---|---|
zip() + List Comprehension |
List of lists | Creating actual matrix structure |
map() + operator.mul
|
List of strings | String repetition operations |
Conclusion
Use zip() with list comprehension when you need a proper matrix structure with sublists. Use map() with operator.mul for simple string repetition operations.
