0

Since I started learning python a few months back, I have been mesmerized about how with the simple code you could achieve complex tasks.

So, I have been trying to do something like this,

list = [1,2,3,4]

statement = ''

if len(list) > 4:
    statement = '[x for x in list if x%%2 == 0]'
else:
    //do something else

I know this won't work as statement above is just a string, but I hope you get the idea of what am trying to do and hope you could suggest how I should go about it.

Sam
  • 86
  • 2
  • 10

1 Answers1

0

i think you are searching for eval function :

Python eval() The eval() method parses the expression passed to this method and runs python expression (code) within the program.

In simple terms, the eval() method runs the python code (which is passed as an argument) within the program.

The syntax of eval() is:

eval(expression, globals=None, locals=None)

eval() Parameters: The eval() takes three parameters:

-expression - this string as parsed and evaluated as a Python expression

-globals (optional) - a dictionary

-locals (optional)- a mapping object. Dictionary is the standard and commonly used mapping type in Python. The use of globals and locals will be discussed later in this article.

Return Value from eval()

The eval() method returns the result evaluated from the expression.

EXAMPLE:

x = 1
print(eval('x + 1'))
list = [1,2,3,4,5]

statement = ''

if len(list) > 4:
    statement = '[x for x in list if x%2 == 0]'
else:
    pass

print(eval(statement)) # [2, 4]
ncica
  • 7,015
  • 1
  • 15
  • 37