How to Create a Matrix in Python?

Estimated read time 1 min read

To create a matrix in Python, you can use a nested list. Here’s an example of how to create a 3×3 matrix in Python:

# Create a 3x3 matrix using a nested list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Display the matrix
for row in matrix:
    for element in row:
        print(element, end=" ")
    print()

In this example, we create a 3×3 matrix using a nested list. The outer list contains three inner lists, each representing a row of the matrix. Each inner list contains three elements, representing the elements in that row.

We then use nested loops to display the matrix. We iterate through each row in the matrix using a for loop, and then iterate through each element in the row using another for loop. We use the print function to display each element, followed by a space, and then a newline character to move to the next row.

Note: You can modify this example to create matrices of different dimensions or with different values.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply