First of all, if your x
only contains a literal of type - strings, numbers, tuples, lists, dicts, booleans, and None - you can use ast.literal_eval
, which is much more safer than eval()
function.
ast.literal_eval(node_or_string)
Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
Also, you will most probably have to define the function isevaluatable()
yourself , example -
def isevaluatable(s):
import ast
try:
ast.literal_eval(s)
return True
except ValueError:
return False
Then you can do
import ast
[ast.literal_eval(x) if isevaluatable(x) else x for x in some_list]
An easier way to do this would be to make the function return the required value itself
def myeval(s):
import ast
try:
return ast.literal_eval(s)
except ValueError:
return s
And then do -
[myeval(x) for x in some_list]