How to Create a Matrix in Python [5 Ways]

In this Python tutorial, we will discuss how to create a matrix in Python using different methods with illustrative examples.

To create a matrix in Python, we can use a list of lists, the NumPy array, the matrix() function, nested for loops, or the map() function. Lists offer a simple approach by nesting lists as rows, while NumPy’s array or matrix() functions provide efficient and feature-rich options. Nested for loops allows for more control in matrix creation, especially for initializing values, and the map() function is useful for generating matrices from user input or other sequential data.

How to create a matrix in Python

There are five different methods present to create a matrix in Python:

  • Using lists
  • Using NumPy array
  • Using matrix() function
  • Using nested loops
  • Using map() function

Let’s see them one by one using some demonstrative examples:

Method 1: Python create matrix using lists

Creating a matrix using a list in Python is straightforward. We can create a matrix as a list of lists, where each inner list represents a row in the matrix.

Example: Here’s an example code to create a matrix in Python and a function to verify if a given list of lists is a matrix.

def create_matrix(rows, cols, value=0):
    return [[value for _ in range(cols)] for _ in range(rows)]

def is_matrix(matrix):
    if not matrix or not isinstance(matrix, list) or not all(isinstance(row, list) for row in matrix):
        return False
    row_length = len(matrix[0])
    return all(len(row) == row_length for row in matrix)

matrix = create_matrix(3, 4)
print("Matrix:", matrix)
print("Is this a matrix?", is_matrix(matrix))

Output: Here,

READ:  NumPy Create an Empty Array in Python [3 Examples]
create_matrix functionThis creates a matrix with given dimensions and fills it with a default value.
is_matrix functionThis checks whether the given structure is a list of lists in Python with equal-length rows, a basic requirement for a structure to be considered a matrix.
Matrix: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Is this a matrix? True
How to create a matrix in Python

This way we can create a matrix in Python using list.

Method 2: How to create matrix in Python using NumPy array

To create a matrix in Python using a NumPy array in Python is a straightforward method.

Example: Here, is an example, where we are going to create a Python matrix:

import numpy as np

matrix = np.array([[1, 2], [3, 4]])

# Printing the matrix
print("Matrix:")
print(matrix)

# Verifying that it's a matrix
print("\nType of the object:", type(matrix))
print("Shape of the matrix:", matrix.shape)

Output: Here, we will create a 2D array using the NumPy library in Python.

Matrix:
[[1 2]
 [3 4]]

Type of the object: <class 'numpy.ndarray'>
Shape of the matrix: (2, 2)
create empty matrix python

This way we can use the 2D array in NumPy to create a matrix in Python.

Method 3: Create a matrix in Python using matrix() function

Use the numpy.matrix() function to create a matrix in Python. We can pass a list of lists or a string representation of the matrix to this function.

Example: Let’s create a 2*2 matrix in Python.

import numpy as np

# Create a matrix using numpy.matrix()
matrix_example = np.matrix([[1, 2], [3, 4]])

# Display the matrix
print("Matrix:")
print(matrix_example)

# Check if it's a numpy matrix
print("\nType of the object:")
print(type(matrix_example))

Output: A 2×2 matrix is created in Python. The type of the created object is then printed out by the type() function.

Matrix:
[[1 2]
 [3 4]]

Type of the object:
<class 'numpy.matrix'>
create matrix python

This way we can use the matrix() function to create a matrix in Python.

READ:  Python Scipy Confidence Interval [9 Useful Examples]

Method 4: How to make a matrix in Python using nested for loop

To create a matrix in Python using nested for loops, we can initialize an empty list and then fill it with sub-lists, where each sub-list represents a row in the matrix. The elements of each row can be defined as needed.

Example: Here, we have to create a matrix in Python using nested for loop.

matrix = []
for i in range(3):
    row = []
    for j in range(3):
        row.append(0)
    matrix.append(row)

# Verifying that the created structure is a matrix
def is_matrix(m):
    if not m:  # Check if the matrix is not empty
        return False
    row_length = len(m[0])
    return all(len(row) == row_length for row in m)

# Displaying the matrix and verification result
print("Matrix:")
for row in matrix:
    print(row)

print("\nIs this a matrix? ", is_matrix(matrix))

Output: Here, we have assigned a 0 value to every element in the matrix.

Matrix:
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

Is this a matrix?  True
define matrix in python

This way we create a matrix in Python using the nested for loop.

Method 5: How to make matrix in Python using the map() function

Creating a matrix in Python using the map() function and user input is a more interactive approach. This method allows us to prompt the user to input the matrix elements row by row.

The map() function is then used to convert the input strings into the desired data type, typically integers or floats.

Example:

rows = int(input("Enter the number of rows: "))
columns = int(input("Enter the number of columns: "))

matrix = []
for i in range(rows):
    row = list(map(int, input(f"Enter row {i+1} elements separated by space: ").strip().split()))[:columns]
    matrix.append(row)

# Print the matrix
for row in matrix:
    print(row)

Output: Here, we are taking the user input and assigning that value to the matrix.

Enter the number of rows: 4
Enter the number of columns: 5
Enter row 1 elements separated by space: 1 2 2 5 6
Enter row 2 elements separated by space: 4 5 6 7 5
Enter row 3 elements separated by space: 0 2 1 5 8
Enter row 4 elements separated by space: 1 9 7 5 0
[1, 2, 2, 5, 6]
[4, 5, 6, 7, 5]
[0, 2, 1, 5, 8]
[1, 9, 7, 5, 0]
how to write matrix in python

This way we can use the map() function to create a matrix in Python.

READ:  Fractal Python Turtle + Examples

Conclusion

Here, we have learned how to create a matrix in Python, using list comprehension, numpy.array(), matrix() function, nested for loop, and map() function with some illustrative examples.

You may also like the following Python tutorials: