pythonmatrixformatting

How should I take a matrix from input?


As we know input makes the inputs to string. How can I take matrix like this ([[1,2],[3,4]]) from input() by user and have it like a normal 2D list to do some thing on it.

It should be like that

data = input([[1,2],[3,4]])
print(data)

output : [[1,2],[3,4]]

I tried this data = list(input()) but it was so wrong.


Solution

  • Using AST

    You can use ast Literals to parse your input string into a list.

    import ast
    
    raw_input = input("Enter the matrix (e.g., [[1,2],[3,4]]): ")
    # Parse the input string as a list
    matrix = ast.literal_eval(raw_input)
    

    Using numpy

    In order to use numpy you would have to enter the matrix in a slightly different format:

    import numpy as np
    
    raw_input = input("Enter the matrix (e.g., 1,2;3,4): ")
    matrix = np.matrix(raw_input, dtype=int)