1

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.

2
  • Seeing as functions are objects, yes, this is possible... What have you tried? Commented Aug 13, 2016 at 5:46
  • Note that you'd have to define statement1 ... statementn in advance (def statement1():... or use lambdas. Commented Aug 13, 2016 at 5:49

6 Answers 6

4

Yes. Functions are first-class-citizens in python: i.e. you could pass them as parameters or even store them in an array.

It is not uncommon to have a list of functions: You could build a simple registry in python like this:

#!/usr/bin/env python

processing_pipeline = []

def step(function):
    processing_pipeline.append(function);
    return function

@step
def step_1(data):
    print("processing step1")

@step
def step_2(data):
    print("processing step2")

@step
def step_3(data):
    print("processing step3")

def main():
    data = {}
    for process in processing_pipeline:
        process(data)

if __name__ == '__main__':
    main()

Here the processing_pipeline is just a list with functions. step is a so called decorator-function, which works like a closure. The python interpreter adds while parsing the file every decorated @step to the pipeline.

And you are able to access the function with an iterator, or via processing_pipeline[i]: try adding processing_pipeline[2](data).

Sign up to request clarification or add additional context in comments.

Comments

0

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!

1 Comment

This answer is the closest to what I was asking considering that it does not require me to define functions. But now is there a way for me to do f=statement to create a function?
0

This is perfectly fine:

def addbla(item):
    return item + ' bla'

items = ['Trump', 'Donald', 'tax declaration']
new_items = [addbla(item) for item in items]
print(new_items)

It adds a political statement to every item in items :)

Comments

0

If you want to run a block of statements, use a function.

def run_statements():
    func()
    for i in range(3):
        if i > 1:
            break
    extra_func()

run_statements()

If you want to choose specific statements from a list, wrap each one in a function:

def looper():
    for i in range(3):
        if i>1:
            break

def func():
    print('hello')

statements = [looper, func]
statements[-1]()

If your statements are simply function calls, you can put them directly into a list without creating wrapper functions.

Comments

0

You can do:

funcs = [min, max, sum]
f = funcs[0]
funcs[1](1,2,3) # out 3
funcs[2]([1,2,3]) # out 6

Comments

0

Since we've had every other way, I thought I'd toss this out:

def a(input):
    return pow(input, 3)

def b(input):
    return abs(input)

def c(input):
    return "I have {0} chickens".format(str(input))

#make an array of functions
foo = [a,b,c]

#make a list comprehension of the list of functions
dop = [x(3) for x in foo]
print dop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.