Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Take Matrix input from user in Python
In this tutorial, we will learn how to take matrix input from the user in Python. There are two common approaches: taking individual elements one by one, or taking entire rows with space-separated values.
Method 1: Taking Individual Elements
This method asks the user to input each matrix element individually ?
Example
# initializing an empty matrix
matrix = []
# taking 2x2 matrix from the user
for i in range(2):
# empty row
row = []
for j in range(2):
# asking the user to input the number
# converts the input to int as the default one is string
element = int(input(f"Enter element [{i}][{j}]: "))
# appending the element to the 'row'
row.append(element)
# appending the 'row' to the 'matrix'
matrix.append(row)
# printing the matrix
print("Matrix:", matrix)
The output of the above code is ?
Enter element [0][0]: 1 Enter element [0][1]: 2 Enter element [1][0]: 3 Enter element [1][1]: 4 Matrix: [[1, 2], [3, 4]]
Method 2: Taking Space-Separated Row Input
This method takes one complete row at a time with space-separated values, then converts each value to integer using map() and int() functions ?
Example
# initializing an empty matrix
matrix = []
# taking 2x2 matrix from the user
for i in range(2):
# taking row input from the user
print(f"Enter row {i + 1} (space-separated): ", end="")
row = list(map(int, input().split()))
# appending the 'row' to the 'matrix'
matrix.append(row)
# printing the matrix
print("Matrix:", matrix)
The output of the above code is ?
Enter row 1 (space-separated): 1 2 Enter row 2 (space-separated): 3 4 Matrix: [[1, 2], [3, 4]]
Dynamic Matrix Size
You can also create a more flexible version that accepts any matrix size ?
Example
# taking matrix dimensions from user
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
matrix = []
print(f"Enter {rows}x{cols} matrix (space-separated rows):")
for i in range(rows):
row = list(map(int, input().split()))
matrix.append(row)
print("Your matrix:")
for row in matrix:
print(row)
The output of the above code is ?
Enter number of rows: 3 Enter number of columns: 3 Enter 3x3 matrix (space-separated rows): 1 2 3 4 5 6 7 8 9 Your matrix: [1, 2, 3] [4, 5, 6] [7, 8, 9]
Comparison
| Method | Input Style | Best For |
|---|---|---|
| Individual Elements | One element per line | Small matrices, clear prompts |
| Space-Separated Rows | Entire row per line | Faster input, larger matrices |
Conclusion
Use Method 1 for small matrices where you want clear prompts for each element. Use Method 2 for faster input when dealing with larger matrices or when users prefer typing entire rows at once.
