Open In App

Take Matrix input from user in Python

Last Updated : 21 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Matrix is nothing but a rectangular arrangement of data or numbers. In other words, it is a rectangular array of data or numbers. The horizontal entries in a matrix are called as ‘rows’ while the vertical entries are called as ‘columns’. If a matrix has r number of rows and c number of columns then the order of matrix is given by r x c. Each entries in a matrix can be integer values, or floating values, or even it can be complex numbers. 

Examples:

// 3 x 4 matrix
     1 2 3 4
M =  4 5 6 7
     6 7 8 9

// 2 x 3 matrix in Python
A = ( [ 2, 5, 7 ],
      [ 4, 7, 9 ] )

// 3 x 4 matrix in Python where entries are floating numbers
B = ( [ 1.0, 3.5, 5.4, 7.9 ],
      [ 9.0, 2.5, 4.2, 3.6 ],
      [ 1.5, 3.2, 1.6, 6.5 ] )

In Python, we can take a user input matrix in different ways. Some of the methods for user input matrix in Python are shown below: 

Code #1: 

Python3




# A basic code for matrix input from user
 
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
 
# Initialize matrix
matrix = []
print("Enter the entries rowwise:")
 
# For user input
for i in range(R):          # A for loop for row entries
    a =[]
    for j in range(C):      # A for loop for column entries
         a.append(int(input()))
    matrix.append(a)
 
# For printing the matrix
for i in range(R):
    for j in range(C):
        print(matrix[i][j], end = " ")
    print()


Output: 

Enter the number of rows:2
Enter the number of columns:3
Enter the entries rowwise:
1
2
3
4
5
6

1 2 3 
4 5 6 

Time complexity: O(RC)
Auxiliary space: O(RC) 

One liner: 

Python3




# one-liner logic to take input for rows and columns
mat = [[int(input()) for x in range (C)] for y in range(R)]


Code #2: Using map() function and Numpy. In Python, there exists a popular library called NumPy. This library is a fundamental library for any scientific computation. It is also used for multidimensional arrays and as we know matrix is a rectangular array, we will use this library for user input matrix. 

Python3




import numpy as np
 
R = int(input("Enter the number of rows:"))
C = int(input("Enter the number of columns:"))
 
 
print("Enter the entries in a single line (separated by space): ")
 
# User input of entries in a 
# single line separated by space
entries = list(map(int, input().split()))
 
# For printing the matrix
matrix = np.array(entries).reshape(R, C)
print(matrix)


Output: 

Enter the number of rows:2
Enter the number of columns:2
Enter the entries in a single line separated by space: 1 2 3 1 
[[1 2]
 [3 1]]

Time complexity: O(RC), as the code iterates through RC elements to create the matrix.
Auxiliary space: O(RC), as the code creates an RC sized matrix to store the entries.



Similar Reads

Take input from user and store in .txt file in Python
In this article, we will see how to take input from users and store it in a .txt file in Python. To do this we will use python open() function to open any file and store data in the file, we put all the code in Python try-except block. Let's see the implementation below. Stepwise Implementation Step 1: First, we will take the data from the user and
2 min read
Take input from stdin in Python
In this article, we will read How to take input from stdin in Python. There are a number of ways in which we can take input from stdin in Python. sys.stdininput()fileinput.input()Read Input From stdin in Python using sys.stdin First we need to import sys module. sys.stdin can be used to get input from the command line directly. It used is for stand
2 min read
How to take integer input in Python?
In this post, We will see how to take integer input in Python. As we know that Python's built-in input() function always returns a str(string) class object. So for taking integer input we have to type cast those inputs into integers by using Python built-in int() function. Let us see the examples: Example 1: C/C++ Code # take input from user input_
2 min read
How to Take Only a Single Character as an Input in Python
Through this article, you will learn how to accept only one character as input from the user in Python. Prompting the user again and again for a single character To accept only a single character from the user input: Run a while loop to iterate until and unless the user inputs a single character.If the user inputs a single character, then break out
3 min read
Python | Numpy matrix.take()
With the help of Numpy matrix.take() method, we can select the elements from a given matrix by passing the parameter as index value of that element. It will return a matrix having one dimension. Remember it will work for one axis at a time. Syntax : matrix.take(index, axis) Return : Return matrix of selected indexes Example #1 : In this example we
1 min read
Get a list as input from user in Python
We often encounter a situation when we need to take a number/string as input from the user. In this article, we will see how to get input a list from the user using Python. Example: Input : n = 4, ele = 1 2 3 4Output : [1, 2, 3, 4]Input : n = 6, ele = 3 4 1 7 9 6Output : [3, 4, 1, 7, 9, 6]Get a list as input from user in Python using Loop C/C++ Cod
2 min read
Python program to create dynamically named variables from user input
Given a string input, our task is to write a Python program to create a variable from that input (as a variable name) and assign it to some value. Below are the methods to create dynamically named variables from user input. Using globals() method to create dynamically named variables Here we are using the globals() method for creating a dynamically
2 min read
Save user input to a Excel File in Python
In this article, we will learn how to store user input in an excel sheet using Python, What is Excel? Excel is a spreadsheet in a computer application that is designed to add, display, analyze, organize, and manipulate data arranged in rows and columns. It is the most popular application for accounting, analytics, data presentation, etc. Methods us
4 min read
How to input multiple values from user in one line in Python?
For instance, in C we can do something like this: C/C++ Code // Reads two values in one line scanf("%d %d", &x, &y) One solution is to use raw_input() two times. C/C++ Code x, y = input(), input() Another solution is to use split() C/C++ Code x, y = input().split() Note that we don't have to explicitly specify spli
2 min read
How To Add User Input To A Dictionary In Python
In Python, a dictionary is a built-in data type that represents an unordered collection of key-value pairs. Dictionaries are sometimes referred to as "dicts." They provide a way to store and retrieve data efficiently based on keys. Dictionaries in Python are defined using curly braces {}. In this article, we will add user input to a dictionary in P
3 min read
Practice Tags :
three90RightbarBannerImg