How to print a matrix in Python
Learn how to print a matrix in Python. Discover different methods, tips, real-world applications, and how to debug common errors.

To print a matrix in Python is a common task for data visualization and analysis. It helps you display a 2D list or array in a readable, grid-like format for easier interpretation.
In this article, you'll explore several techniques to print matrices. You'll find practical tips, see real-world applications, and get advice to debug common issues, helping you master matrix display.
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 nested loop to traverse the matrix. The outer loop iterates through each row, and the inner loop processes each element within that row. The formatting relies on two key uses of the print() function:
- Inside the inner loop,
print(element, end=" ")prints each number followed by a space instead of a newline. This keeps all elements of a row on the same line. - After the inner loop finishes, a standalone
print()call adds a newline character. This ensures the next row starts on a new line, creating the matrix's grid structure.
Standard printing techniques
If the nested loop approach feels a bit manual, you can use more specialized tools like the pprint module, list comprehensions with join(), or NumPy's array.
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]]
Python's pprint module, short for "pretty-print," is designed to display complex data structures in a more readable format. When you pass a matrix to the pprint() function, it automatically handles the formatting, presenting the data in a clean, organized way.
- It preserves the list-of-lists structure, including brackets and commas, which is useful for debugging.
- The output clearly shows the object's structure without needing manual loops.
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 technique offers a more compact way to format your matrix using a list comprehension and the join() method. For each row, it first converts every integer element into a string so they can be joined together.
- The generator expression
(str(element) for element in row)efficiently handles the number-to-string conversion. - Next,
' '.join()concatenates these strings into a single line, placing a space between each one. - Finally,
print()displays the formatted row and moves to the next line, creating a clean grid.
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]]
NumPy is a go-to library for numerical computing in Python. When you convert a list of lists into a NumPy array using np.array(), printing it becomes incredibly simple. The print() function automatically formats the array into a clean, grid-like output.
- It aligns the columns for better readability.
- It removes the commas between elements, presenting a more mathematical matrix look.
This approach is not only concise but also highly efficient, especially when you're working with large matrices for data science or scientific tasks.
Advanced printing techniques
For more fine-grained control over your matrix's appearance, you can use advanced tools like pandas DataFrame, f-strings, or NumPy's set_printoptions().
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 powerful tool for working with tabular data. When you convert your matrix into a DataFrame with pd.DataFrame(matrix), printing it yields a clean, structured table. This is especially useful for data analysis.
- The
DataFrameautomatically adds row and column indices, making your data easy to reference. - It's ideal for when you need more than just a simple grid, offering a foundation for further manipulation and analysis.
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 approach gives you precise control over spacing by combining f-strings with the join() method. It's perfect for creating neatly aligned columns, regardless of the numbers' digit counts.
- The magic is in the format specifier
f'{element:3d}'. The:3dpart instructs Python to format each integer (d) to a width of three characters. - This pads smaller numbers with leading spaces, ensuring every element in a column aligns perfectly.
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 precise control over how arrays are displayed, which is especially handy for matrices with floating-point numbers. You set these options once, and they apply to all NumPy arrays you print from that point on.
- The
precision=2argument limits the output to two decimal places for cleaner formatting. suppress=Trueprevents Python from using scientific notation for very large or small numbers.linewidth=100defines the maximum number of characters per line before the output wraps.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the matrix printing techniques we've explored, Replit Agent can turn them into production tools:
- Build a data visualizer that generates a formatted heatmap from spreadsheet data.
- Create a Sudoku board validator that displays the grid and checks for errors.
- Deploy a scientific calculator that performs matrix operations and displays the results in a clean, aligned format.
Simply describe your application, and Replit Agent will write the code, run tests, and deploy it for you.
Common errors and challenges
Even with the right tools, you might run into a few common roadblocks when printing matrices, but they're usually simple to fix.
- Fixing type errors when using
join()with numeric matrices. You'll often see aTypeErrorwhen you try to use thejoin()method on a list containing numbers. This is becausejoin()is designed to work only with strings. The solution is to convert each number to a string before joining, for example, by using a generator expression like' '.join(str(element) for element in row). - Handling alignment issues with f-string formatting. When numbers in your matrix have different digit counts, simple printing can result in messy, misaligned columns. You can solve this with f-strings by specifying a fixed width for each element. Using a format specifier like
f'{element:3d}'pads smaller numbers with leading spaces, ensuring all your columns line up perfectly. - Dealing with truncated output when printing large matrices. To avoid overwhelming your console, libraries like NumPy and pandas often shorten the display of large matrices with ellipses (
...). If you need to see the entire grid, you can override this default behavior. In NumPy, usenp.set_printoptions(threshold=np.inf). In pandas, you can usepd.set_option('display.max_rows', None)to show all rows.
Fixing type errors when using join() with numeric matrices
It's a classic snag: you try to use the join() method on a row of numbers and get hit with a TypeError. This happens because join() is built to work only with strings, not integers. See what happens in the code below.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
print(' '.join(row)) # This will cause TypeError
The code attempts to join the elements in row, but since the row contains numbers instead of strings, a TypeError is triggered. Take a look at the corrected code below to see how this is resolved.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
print(' '.join(str(element) for element in row))
The fix works by converting each number into a string before the join() method is called. It uses a generator expression, (str(element) for element in row), to apply the str() function to every element. Then, ' '.join() can successfully concatenate these strings with a space in between. You'll run into this situation anytime you need to format a list of numbers into a single line of text for display.
Handling alignment issues with f-string formatting
When your matrix contains numbers with different digit counts, simple printing can create a messy, unaligned grid that makes the data hard to read. The code below shows what happens when you use a basic f-string with join() without controlling spacing.
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 f-string f'{element}' converts each number to a string but doesn't pad the values to a consistent width. This is why the columns become misaligned. See how a small change in the code below solves this.
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 f-string format specifier f'{element:3d}'. This small addition gives you precise control over the output's alignment.
- The
:3dpart instructs Python to format each integer (d) to a width of three characters. - It automatically pads smaller numbers with leading spaces to fill the specified width.
This simple trick creates perfectly aligned columns, which is crucial anytime you're displaying numerical data and want it to be easy to read.
Dealing with truncated output when printing large matrices
When working with large matrices, you'll notice libraries like NumPy and pandas often shorten the output with ellipses. This feature prevents overwhelming your console, but it's unhelpful when you need to see every single value. The code below demonstrates this truncation.
import numpy as np
large_matrix = np.random.rand(10, 10)
print(large_matrix) # Output truncated with ... in the middle
The code generates a large array, and NumPy's default print() behavior automatically shortens it to keep the output tidy. See how you can override this default in the code below to display the entire matrix.
import numpy as np
large_matrix = np.random.rand(10, 10)
np.set_printoptions(threshold=np.inf, precision=3)
print(large_matrix)
The fix involves changing NumPy's global print settings. By using np.set_printoptions(), you can force NumPy to show the entire array.
- Setting
threshold=np.inftells NumPy to never truncate the output, regardless of the matrix size. - The
precision=3argument is also used to format floating-point numbers to three decimal places for better readability.
This approach is crucial when you need to inspect every value in a large dataset without summarization.
Real-world applications
Mastering these printing techniques opens the door to practical applications, from building a simple game board to visualizing machine learning results.
Printing a tic-tac-toe game board with print()
Printing a tic-tac-toe board is a great practical example that uses the print() function and join() method to add visual separators, turning a simple matrix into a recognizable game grid.
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 builds the tic-tac-toe grid by iterating through each row. The ' | '.join(row) expression is key—it takes the list of characters in a row and connects them with vertical separators. The surrounding print() function then adds the outer vertical bars to frame the board.
- An
ifstatement checks if the current row is not the last one by comparing it togame_board[-1]. - This ensures the horizontal separator,
'-------------', is only printed between the rows, not after the final one, creating a clean visual output.
Visualizing confusion matrices for classification results
A confusion matrix is a key tool in machine learning, and visualizing it as a heatmap using libraries like Seaborn makes it easy to evaluate a 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 to turn a NumPy array into a visual heatmap. The core of the visualization is the sns.heatmap() function, which handles the heavy lifting of plotting the data.
- The
annot=Trueargument writes the data value inside each cell of the grid. fmt='d'ensures these numbers are formatted as integers, not decimals.cmap='Blues'sets the color scheme, making higher values appear darker.
Finally, matplotlib functions like plt.xlabel() and plt.title() add context by labeling the axes and giving the chart a title.
Get started with Replit
Turn your new skills into a functional tool. Describe what you want to build to Replit Agent, like "create a matrix calculator that displays results in a clean grid" or "build a tool that converts CSV data into a formatted ASCII table."
The agent will write the code, test for errors, and deploy your application for you. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.



%2520in%2520Python.png)