Act fast, special offers end soon! Up to $294 is savings when you get Premium today.
Get offer codes

What is ast.literal_eval

On a different platform, i noticed, that even though input is available in list type , the code prior to the mission mentioned the following z2 lines. Why is this required to execute the code and why the code is failing without it?

import ast
variable = ast.literal_eval(input())

Given the import statement, it’s probably Abstract Syntax Trees. You can google for what they do or check out the documentation.

Why that platform uses it would depend on what they are doing with it. That’s something best inquired on that platform, I think. But you can look up about them and what literal_eval() does to probably get a better idea in relation to the rest of the code.

That looks like some setup code that platform runs. Can you share what the platform is and how to see what you’re asking about?

1 Like

I used it once after some web scraping. It can convert a string type into a list
For example if you scrap data you’ll only get string type as far as I know, let’s say you have
something that looks like this

In the last column of the dataframe I have in the first row:
[‘Candidate Master (CM)’, ‘2012’], the last column is of object dtype.

It converts ‘[‘Candidate Master (CM)’, ‘2012’]’ (str) to [‘Candidate Master (CM)’, ‘2012’] (list).

To answer your question, your code would convert your string input [‘blabla’, ‘bla’] to a list with first element being ‘blabla’ and the second ‘bla’. I am not very familiar with the input function but I guess it’s just to be more user-friendly

Here is another example

Hope it helps!

2 Likes