- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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.

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)

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']]

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.

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)

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 Questions & Answers
- 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
- Python - Count the frequency of matrix row length
- Find maximum path length in a binary matrix in Python
- 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?
- Find length of the largest region in Boolean Matrix in C++
- Find Maximum side length of square in a Matrix in C++
- Matrix manipulation in Python
- Initialize Matrix in Python

Advertisements