black laptop computer displaying blue screen
Photo by Sean Lim on Unsplash

Sometimes you may get an input that is a string, but you actually need it to be a list, or a list of lists.

There are many alternatives that you can use to convert such strings into lists, or list of lists, but in this article, I am going to mention here a really quick way.

You don’t need to learn regular expressions, or spend many hours trying to consider the edge cases. You can simply use a method included in the module called ast.

Let us illustrate it with some quick examples.

Let’s say that you get an input in a function that is a string, but it is supposed to be a list:

You don’t need it in that format. You need it to be a list:

Or maybe you the following response from an API call:

Rather than bothering with complicated regular expressions, all you have to do is import the module ast and then call its method literal_eval:

That’s all you need to do.

Now you will get the result as a list, or list of lists, namely like the following:

That’s it. I hope you find this useful.