
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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 articled we will see how to create a matrix with required number of elements when the elements are given as a list.
Using zip
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 we can create the resulting matrix which will involve a for loop to organize the elements.
Example
listA = ['m', 'n', 'p','q'] # Count of elements elem_count = [1,0,3,2] # Given Lists print("Given List of elements: " ,listA) print("Count of elements : ",elem_count) # Creating Matrix res = [[x] * y for x, y in zip(listA, elem_count)] # Result print("The new matrix is : " ,res)
Output
Running the above code gives us the following result −
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']]
with map and mul
In this approach we use the mul method from operator module in place of zip method above. Also the map function applies the mul method to every element in the list hence the for loop is not required.
Example
from operator import mul listA = ['m', 'n', 'p','q'] # Count of elements elem_count = [1,0,3,2] # Given Lists print("Given List of elements: " ,listA) print("Count of elements : ",elem_count) # Creating Matrix res = list(map(mul, listA, elem_count)) # Result print("The new matrix is : " ,res)
Output
Running the above code gives us the following result −
Given List of elements: ['m', 'n', 'p', 'q'] Count of elements : [1, 0, 3, 2] The new matrix is : ['m', '', 'ppp', 'qq']
- Related Articles
- Add custom borders to a matrix in Python
- Program to find length of longest matrix path length in Python
- Python – Sort Matrix by Maximum String Length
- Find maximum path length in a binary matrix in Python
- Python - Count the frequency of matrix row length
- Python Program to sort rows of a matrix by custom element count
- Program to length of longest increasing path in a given matrix in Python
- Custom len() Function In Python
- Custom list split in Python
- Python Program that prints the rows of a given length from a matrix
- How to implement a custom Python Exception with custom message?
- Matrix manipulation in Python
- Initialize Matrix in Python
- Rotate Matrix in Python
- Custom Multiplication in list of lists in Python
