0

How to convert an input 2D array to a 2D list?
For example:

The user inputs: [[2,3], [3,4]]

This is read as a string when I read it from standard input using input() method. But I want it as a list of lists in python.

for eg: a = [[2,3], [3,4]]
type(a)
<class, 'list'>

Is there an inbuilt function or library for it? How to do it? I am trying but can't resolve it.

Kumar
  • 173
  • 1
  • 12
  • 1
    `ast.literal_eval` handles basically anything that a) looks like an **expression** in Python source code, b) doesn't require looking up any names (variables, functions, classes etc.) and c) doesn't involve any language keywords or operators. So, any kind of nested structure of *literal* data. – Karl Knechtel Sep 05 '22 at 04:57

1 Answers1

2

You are looking for ast.literal_eval, consider following simple example

import ast
user_input = "[[2,3], [3,4]]" # str
a = ast.literal_eval(user_input)
print(isinstance(a,list))

output

True

ast is part of standard library.

Daweo
  • 31,313
  • 3
  • 12
  • 25