How to Create a Matrix in Python Using Lists?

Estimated read time 1 min read

You can create a matrix in Python using lists by using nested lists to represent the rows and columns of the matrix. Here’s an example of how to create a 2×2 matrix using lists:

# Create a 2x2 matrix using nested lists
matrix = [[1, 2], [3, 4]]

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

In this example, we create a 2×2 matrix using nested lists. The outer list contains two inner lists, each representing a row of the matrix. Each inner list contains two 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