How to print a matrix in Python

Learn how to print a matrix in Python. Explore different methods, tips, real-world applications, and common error debugging.

How to print a matrix in Python
Published on: 
Fri
Feb 13, 2026
Updated on: 
Mon
Apr 13, 2026
The Replit Team

Printing a matrix in Python is a common task for data visualization and debugging. Python offers several ways to display these two-dimensional arrays, from simple loops to specialized library functions.

Here, we'll guide you through several techniques for clear matrix printing. You'll find practical tips for custom formatting, explore real-world applications in data analysis, and get essential debugging advice for your projects.

Basic printing with nested loops

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
print(element, end=" ")
print() # New line after each row--OUTPUT--1 2 3
4 5 6
7 8 9

This method uses a classic nested loop to process each row and then each element, which is effective for creating lists of lists. The real trick to the formatting lies in how the print() function is used.

  • print(element, end=" "): This prints each number but replaces the default newline with a space. It’s what keeps all elements of a row on the same line.
  • print(): After the inner loop finishes, this call adds a single newline, ensuring the next row starts on a new line, which creates the final matrix structure.

Standard printing techniques

While nested loops are a good start, Python’s built-in tools and specialized libraries offer more direct and readable ways to print your matrices.

Using the pprint module

from pprint import pprint
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
pprint(matrix)--OUTPUT--[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

The pprint module, short for “pretty-print,” is built into Python to format complex data structures cleanly. It's especially useful for nested lists like our matrix. The module automatically handles line breaks and indentation to improve readability, making your output much cleaner.

  • Unlike a standard print(), pprint() presents the matrix in a way that's not just easy on the eyes but is also valid Python syntax. This makes it great for debugging.

Using list comprehensions and join()

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
print(' '.join(str(element) for element in row))--OUTPUT--1 2 3
4 5 6
7 8 9

This approach combines a list comprehension with the join() string method for a compact and efficient solution. It processes each row, converts its elements to strings, and then joins them with a space. This method is often favored for its readability and "Pythonic" style.

  • The expression str(element) for element in row iterates through each number in a row and converts it into a string. This is a necessary step because join() only works with strings.
  • The ' '.join() method then takes these new string elements and concatenates them into a single line, separated by spaces.

Using NumPy's array for matrix printing

import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(matrix)--OUTPUT--[[1 2 3]
[4 5 6]
[7 8 9]]

The NumPy library is a powerhouse for numerical computing in Python. When you convert a list into a NumPy array, printing it gives you a clean, matrix-like format automatically. Notice how the output is neatly aligned without commas separating the elements.

  • This formatting is built-in, making it perfect for data analysis and scientific tasks where readability is key.
  • Simply passing the NumPy array to the print() function is all you need to get this clean display.

Advanced printing techniques

For situations that demand more than a standard printout, you can leverage more powerful tools for tabular displays or fine-tune formatting with custom options.

Using pandas DataFrame for tabular display

import pandas as pd
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
df = pd.DataFrame(matrix)
print(df)--OUTPUT--0 1 2
0 1 2 3
1 4 5 6
2 7 8 9

The pandas library is a go-to for data analysis, and its DataFrame object is perfect for creating tabular displays. By converting your list of lists into a DataFrame, you get a clean, spreadsheet-like output when you print it.

  • The output automatically includes row and column indices, making it easy to reference specific data points.
  • This method is especially useful when you plan to perform further data analysis, as you're already working within the powerful pandas ecosystem.

Using formatted string literals (f-strings)

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
print(' '.join(f'{element:3d}' for element in row))--OUTPUT--1 2 3
4 5 6
7 8 9

This method gives you precise control over spacing using formatted string literals, or f-strings. Learning more about using f-strings in Python helps when combining the join() method with custom formatting for perfect alignment, which is ideal for matrices with numbers of varying lengths.

  • The key is the expression f'{element:3d}', which tells Python how to format each number.
  • The format specifier :3d allocates a width of three characters for each integer (the d). This pads numbers with leading spaces, ensuring every column lines up neatly.

Using NumPy with custom set_printoptions()

import numpy as np
matrix = np.array([[100.123, 200.456, 300.789],
[400.123, 500.456, 600.789],
[700.123, 800.456, 900.789]])
np.set_printoptions(precision=2, suppress=True, linewidth=100)
print(matrix)--OUTPUT--[[ 100.12 200.46 300.79]
[ 400.12 500.46 600.79]
[ 700.12 800.46 900.79]]

NumPy’s set_printoptions() function gives you fine-grained control over how arrays are displayed. It’s perfect for standardizing output across a project, especially when dealing with floating-point numbers. This function adjusts the print settings for the rest of your session.

  • precision=2 limits the output to two decimal places, rounding the numbers for you.
  • suppress=True stops NumPy from using scientific notation, forcing a standard decimal format.
  • linewidth=100 sets the maximum line width, which prevents long rows from wrapping unexpectedly.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. You can describe what you want to build, and Agent 4 handles everything from writing the code to connecting databases and deploying it live.

Instead of piecing together techniques, you can describe the app you actually want to build and the Agent will take it from an idea to a working product:

  • A report generator that formats raw matrix data into a perfectly aligned table for easy reading.
  • A game board generator that creates and displays a grid for tic-tac-toe or a simple text-based adventure.
  • A data analysis tool that converts a list of lists into a structured DataFrame, complete with headers and column summaries.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Even with the right tools, you might run into a few common roadblocks when printing matrices, but they're all straightforward to fix.

  • Fixing type errors when using join() with numeric matrices
  • A TypeError is a frequent hurdle when using the join() method. This error occurs because join() is designed to work only with strings, not integers or floats. The fix is to explicitly convert each number to a string using str() before the join() operation is called.
  • Handling alignment issues with f-string formatting
  • Alignment can get messy when your matrix contains numbers with different digit counts, causing columns to look uneven. Using f-string formatting gives you control over this. By specifying a width, such as in f'{element:4d}', you force each number to occupy a fixed space, with padding added to shorter numbers for a clean, tabular look.
  • Dealing with truncated output when printing large matrices
  • Libraries like NumPy and pandas often truncate large matrices, replacing data with ellipses (...) to keep the output manageable. You can override this in NumPy with np.set_printoptions(threshold=np.inf) or in pandas by setting pd.set_option('display.max_rows', None) to display all rows.

Fixing type errors when using join() with numeric matrices

The join() method is a powerful tool for formatting, but it has one strict rule: it only works on strings. When you try to use it directly on a list of numbers, Python will raise a TypeError. This is a common mix-up.

You'll run into this error if you try to join a row of integers without converting them first. The code below demonstrates what happens.

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
print(' '.join(row)) # This will cause TypeError

The ' '.join() method is called on row, which contains integers, not the required strings. This mismatch causes the error. The corrected code below shows how to properly prepare the data for joining.

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
print(' '.join(str(element) for element in row))

The solution is a generator expression, str(element) for element in row, which converts each number to a string before join() sees it. This simple step provides join() with the string sequence it requires, resolving the TypeError. You’ll want to remember this fix anytime you’re building a string from a list that contains numbers or other non-string objects.

Handling alignment issues with f-string formatting

When your matrix contains numbers of varying lengths, a simple f-string join can result in a messy, unaligned grid. The columns won't line up, making the output difficult to read and defeating the purpose of a clean matrix display.

The code below demonstrates this common alignment problem, where the visual structure of the matrix is lost.

matrix = [[1, 200, 3], [40, 5, 600], [7, 800, 9]]
for row in matrix:
print(' '.join(f'{element}' for element in row)) # Unaligned output

The expression f'{element}' converts each number to a string but doesn't add padding for shorter numbers, causing the columns to misalign. The corrected code below shows how to fix this with a simple format specifier.

matrix = [[1, 200, 3], [40, 5, 600], [7, 800, 9]]
for row in matrix:
print(' '.join(f'{element:3d}' for element in row))

The solution lies in the format specifier :3d within the f-string. This instructs Python to allocate a minimum of three character spaces for each integer (the d). Shorter numbers get padded with leading spaces, which forces every column to align perfectly. Keep this technique in mind whenever your matrix contains numbers of different lengths, as it ensures your output is always a clean, readable grid.

Dealing with truncated output when printing large matrices

When you print a large matrix, libraries like NumPy and pandas often shorten the output to keep it readable. They replace middle rows and columns with ellipses (...) to avoid flooding your console. The following code demonstrates this default behavior.

import numpy as np
large_matrix = np.random.rand(10, 10)
print(large_matrix) # Output truncated with ... in the middle

By default, NumPy’s print() function condenses large arrays to keep the output tidy, which is why you see ellipses. To display the entire matrix without truncation, you'll need to adjust NumPy's print settings as shown below.

import numpy as np
large_matrix = np.random.rand(10, 10)
np.set_printoptions(threshold=np.inf, precision=3)
print(large_matrix)

The solution is to use NumPy’s set_printoptions() to adjust its global display settings. This gives you direct control over how arrays appear when printed.

  • threshold=np.inf tells NumPy to show the entire matrix, which removes the size limit that causes truncation.
  • precision=3 is an optional but handy addition that formats numbers to three decimal places, keeping the output clean.

This is your go-to fix whenever you need to inspect every single element in a large array without summarization.

Real-world applications

With these formatting skills, you can build practical applications through vibe coding, from simple game boards to complex data visualizations for machine learning models.

Printing a tic-tac-toe game board with print()

You can use basic print() functions and the join() method to render a simple matrix into a classic tic-tac-toe game board.

game_board = [['X', 'O', 'X'],
[' ', 'X', 'O'],
['O', ' ', 'X']]

for row in game_board:
print('|', ' | '.join(row), '|')
if row != game_board[-1]:
print('-------------')

This code snippet renders the game board by looping through each row. The real work happens in two main steps:

  • The ' | '.join(row) expression inserts vertical separators between the 'X' and 'O' markers, and an outer print() wraps each row with side borders.
  • An if statement checks if the current row is not the last one before printing a horizontal line, which keeps a separator from appearing at the bottom of the grid.

This combination of string joining and conditional printing creates the final board structure.

Visualizing confusion matrices for classification results

Matrix formatting is crucial in machine learning, where a confusion matrix can be visualized as a heatmap to give you an at-a-glance summary of your model's performance.

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

confusion_matrix = np.array([[45, 5], [8, 42]])
class_names = ['Negative', 'Positive']

plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix, annot=True, fmt='d', cmap='Blues',
xticklabels=class_names, yticklabels=class_names)
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.title('Confusion Matrix')

This code uses the Seaborn library’s heatmap() function to visualize the confusion_matrix data. It’s a powerful way to turn raw numbers into an intuitive graphic. The plot is customized with a few key arguments:

  • annot=True displays the numerical values directly on the colored cells.
  • fmt='d' ensures these numbers are formatted as integers, not scientific notation.
  • cmap='Blues' sets the color palette, making higher values appear darker.

Finally, matplotlib functions like plt.xlabel() and plt.title() add the necessary labels and a title to complete the visualization.

Get started with Replit

Now, turn these techniques into a real tool. Tell Replit Agent to build a "heatmap generator for a small dataset" or a "text-based maze generator that prints the grid to the console."

Replit Agent writes the code, tests for errors, and deploys your app directly from your prompt. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.