Let's explore different methods to print a 2D matrix in Python:
Method 1: Using Nested Loops.
One of the simplest ways to print a 2D matrix is by utilizing nested loops to iterate through rows and columns.
Python Code:
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # Using nested loops to print the matrix for row in matrix: for element in row: print(element, end=" ") print() # Move to the next line after printing a row
1 2 3
4 5 6
7 8 9
Method 2: Using List Comprehension.
Python's list comprehension offers a concise way to print a 2D matrix.
Python Code:
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] # Using list comprehension to print the matrix [print(*row) for row in matrix]
Output:
1 2 3
4 5 6
7 8 9
Method 3: Using NumPy Library.
The NumPy library provides powerful functionalities for handling multi-dimensional arrays, including 2D matrices.
Python Code:
import numpy as np matrix = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) # Printing the NumPy matrix print(matrix)
Output:
1 2 3
4 5 6
7 8 9
No comments:
Post a Comment