Print Matrix in Python

Outline: To print matrix in Python use –

  • numpy. array() method, or,
  • numpy.matrix class, or,
  • a list comprehension + join() method
  • join() + map() methods

❖ Overview

A matrix is a two-dimensional data structure consisting of elements arranged in rows and columns. For example:

The above figure represents a 4×3 matrix since it has four rows and three columns.

Now that you know what a matrix is let us dive into the mission-critical question –

Problem Statement: Given a matrix as an input, how will you print and display it as an output in Python?

You might be wondering – “Can’t I simply print the matrix by storing it in a variable?”🤔 Unfortunately, it won’t print the input matrix. Instead, it will generate a list of lists, as shown below.

❖ Method 1: Using The NumPy Library

Python comes with a multitude of extremely powerful libraries which allow you to work with huge amounts of data with ease.

NumPy is a library in Python that is used for scientific computing and supports powerful functions to deal with N-dimensional array objects. It also provides us with functions for working in the domains of linear algebra, fourier transform, and matrices.

📓 Note: You need to install NumPy before you can use it. You can install it using –

pip install numpy

Let’s have a look at the different ways to create and print a matrix in Python using NumPy.

1️⃣ Using numpy.array()

The array() method of the NumPy library allows you to create a matrix object.

Example:

Output:

[[0 1 4 2 3]
[4 2 0 1 5]
[2 2 1 0 3]
[3 4 5 3 0]]

2️⃣ Using numpy.matrix()

The numpy.matrix() class returns a matrix from an array-like object or a string of data.

Syntax:

numpy.matrix(data, dtype = None)

Example:

Output:

[[0 1 4 2 3]
[4 2 0 1 5]
[2 2 1 0 3]
[3 4 5 3 0]]

⚠️Caution: It is not recommended to use this class anymore. Instead, you should opt for regular arrays. The class may be removed/deprecated in the future.

TRIVIA

❖ Method 2: Using List Comprehension and join

✏️ In simple words, a list comprehension is a crisp and compact way of creating Python lists.

Syntax: [expression for item in iterable if condition == True]

Example:

✏️ join() is a function in Python that takes the items of an iterable and combines them into a single string.

Example:

Thus, you can leverage the functionality of a list comprehension along with the join method to print a matrix.

Example:

Output:

0 1 4 2 3
4 2 0 1 5
2 2 1 0 3
3 4 5 3 0

You can also use a nested for loop to replicate the above concept.

But, the above code will result in 24 print statements as opposed to a single print statement in case of the list comprehension.

❖ Method 3: Using join()+map()

✏️ map( ) is an inbuilt method in Python that takes a function and an iterable as an input. It then executes the function by passing the iterable as an input to the function.

Syntax:

map(functioniterables)

Example:

Output:

0 1 4 2 3
4 2 0 1 5
2 2 1 0 3
3 4 5 3 0

Explanation:

  • the for loop allows you to iterate through each individual array/row within the matrix.
  • map(str, i) converts all the items within each row to a string and then,
  • '\t'.join combines the individual items in a single string, and then each row gets printed one by one.

Conclusion

Thus, this article unveiled numerous methods to print a matrix in Python. The simplest and the most effective way to print a matrix in Python is undoubtedly the numpy.array() method as it takes care of all arrangements and dimensions without any interference for the user.

Read here: [Fixed] ModuleNotFoundError: No module named ‘numpy’

With that, we come to the end of this tutorial. Please subscribe and stay tuned for more interesting discussions in the future. Happy coding! 📚

That’s all about how to print matrix in Python.

Related Posts

  • Detect keypress in Python
    12 June

    Detect keypress in Python

    Table of ContentsUsing the keyboard module to detect keypress in PythonUsing the pynput module to detect keypress in PythonUsing the msvcrt module to detect keypress in Python Python allows us to work with user input in its programs. We can also work with hardware devices in Python. In this article, we will discuss how to […]

  • Copy a dictionary in Python
    12 June

    7 ways to copy a dictionary in python

    Table of ContentsUsing the copy() function to copy a dictionary in PythonUsing the deepcopy() function to copy a dictionary in PythonUsing the dict() function to copy a dictionary in PythonUsing the unpack operator ** to copy a dictionary in PythonUsing the update() function to copy a dictionary in PythonUsing the dictionary comprehension method to copy […]

  • Escape quotes in Python
    11 June

    Escape quotes in Python

    Table of ContentsUsing \ to escape quotes in PythonUsing \ with replace() to escape quotes in PythonUsing json.dumps to escape quotes in PythonUsing triple single or double quotes to escape quotes in pythonUse r to include \ and quotes in String 💡 Outline You can use \ to escape quotes in Python. If you want […]

  • Sleep for milliseconds in python
    31 May

    How to sleep for milliseconds(ms) in Python

    Table of ContentsUse time.sleep() function to make the program sleep for millisecondsUse threading.Timer() function to make the program sleep for milliseconds 💡 Outline You can use time.sleep() method to sleep for milliseconds in Python. If you want to delay python program by 500 ms, then you need to pass 0.5 as parameter to sleep method. […]

  • Convert unix timestamp to datetime in Python
    21 May

    Convert Unix timestamp to DateTime in python

    Table of ContentsUsing fromtimestamp() FunctionUsing strftime() FunctionUsing to_datetime() Function A UNIX timestamp is defined as the several numbers of seconds between a particular date and the Epoch i.e January 1, 1970 at UTC. In this tutorial, we will see some methods by which we can convert a UNIX timestamp to DateTime in Python. Using fromtimestamp() […]

  • Python round to 2 decimal places
    21 May

    How to round to 2 decimals in Python

    Table of ContentsUsing the round() functionUsing the format() functionUsing the % formattingUsing the f-stringsUsing the math.ceil() and math.floor() functions In Python, we deal with integers, floating values, and even imaginary numbers. Float numbers are used to represent the real numbers with integers and decimal parts. Python represents such numbers with 64-bit precision giving it a […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.