pooya13 pooya13 - 3 months ago 6
Python Question

Python - List of Assignments

Is there a way to have

statements = [statement1, statement2, statement3, ...]


in Python?

I want to be able to do:

run statements[i]


or:

f = statements[j]
(where f is a function)

P.S. I want to have a list of assignment statements (lambda would not work) and I rather not create functions. For example:

switch = [output = input, output = 2 * input, output = input ** 2]


Is there any other way than defining a function for each entry?

Thank you everyone who answered my question.

Answer

I want to be able to do: run statements[i]

well, you can do that by exec:

statements = ["result=max(1,2)","print(result)"]
for idx in range(len(statements)):
    exec(statements[idx])
print(result)

Hope it helps!