How to Print a Matrix in Python: Simple Examples and Tips
To print a matrix in Python, you can use nested
for loops to print each row on a new line. Alternatively, use print() with unpacking and the sep parameter for cleaner output.Syntax
To print a matrix (a list of lists) in Python, use nested loops where the outer loop goes through each row and the inner loop prints each element in that row. Use print() to output elements and rows.
for row in matrix:loops through each row.for element in row:loops through each element in the row.print(element, end=' ')prints elements on the same line separated by space.print()after inner loop moves to the next line for the next row.
python
for row in matrix: for element in row: print(element, end=' ') print()
Example
This example shows how to print a 3x3 matrix with each row on its own line and elements separated by spaces.
python
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for element in row:
print(element, end=' ')
print()Output
1 2 3
4 5 6
7 8 9
Common Pitfalls
One common mistake is printing the whole row directly, which prints the list with brackets and commas, making it harder to read. Another is forgetting to add print() after printing a row, causing all elements to print on one line.
python
# Wrong way: prints list with brackets and commas matrix = [[1, 2], [3, 4]] for row in matrix: print(row) # Right way: prints elements cleanly for row in matrix: for element in row: print(element, end=' ') print()
Output
[1, 2]
[3, 4]
1 2
3 4
Quick Reference
Tips for printing matrices in Python:
- Use nested loops to print each element.
- Use
end=' 'inprint()to stay on the same line. - Call
print()after each row to move to the next line. - For simple display,
print(row)shows the row as a list but includes brackets.
Key Takeaways
Use nested loops to print each element of a matrix row by row.
Add print() after each row to start a new line for clean output.
Avoid printing rows directly to prevent brackets and commas in output.
Use print(element, end=' ') to print elements on the same line separated by spaces.