Python Program to Print 2D Matrix.

Printing a 2D matrix in Python is a fundamental operation, often encountered in various data manipulation and algorithmic tasks. A 2D matrix, also known as a 2D array, represents data in a grid format consisting of rows and columns. Python offers several methods to effectively display and print a 2D matrix.

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
Output:
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 

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS