# Take Matrix input from user in Python

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to learn how to take matric input in Python from the user. We can take input from the user in two different ways. Let's see two of them.

## Method 1

Taking all numbers of the matric one by one from the user. See the code below.

## 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())
# appending the element to the 'row'
row.append(element)
# appending the 'row' to the 'matrix'
matrix.append(row)
# printing the matrix
print(matrix)

## Output

If you run the above code, then you will get the following result.

1
2
3
4
[[1, 2], [3, 4]]

## Matrix 2

Taking one row at a time with space-separated values. And converting each of them to using map and int function. See the code.

## Example

# initializing an empty matrix
matrix = []
# taking 2x2 matrix from the user
for i in range(2):
# taking row input from the user
row = list(map(int, input().split()))
# appending the 'row' to the 'matrix'
matrix.append(row)
# printing the matrix
print(matrix)

## Output

If you run the above code, then you will get the following result.

1 2
3 4
[[1, 2], [3, 4]]

## Conclusion

If you have queries in the tutorial, mention them in the comment section.

Published on 11-Jul-2020 11:39:41