1

I have the following lists

fncs = ["MyLinkedList","addAtHead","get","addAtTail"]
args = [[],[8],[1],[81]]

And I want to return

[MyLinkedList(), addAtHead(8), get(1), addAtTail(81)]

I thought I could use fnc_vals = [f(x) for f, x in zip(fncs, args)] but that doesn't seem to work since my fncs list is a list of strings. How can I apply a list of functions to a list of arguments (in Python)?

1
  • should fncs be a list of strings? Commented Apr 18, 2019 at 10:29

2 Answers 2

1

If you have a list of strings refering to the current scope functions you can use globals or locals:

fnc_vals = [golbals()[f](x) for f, x in zip(fncs, args)]

Check this example:

>>> def foo(x):
...     return x
... 
>>> globals()["foo"](10)
10

You can also build your own functions addressing dictionary:

>>> def foo(x):
...     return x
... 
>>> def bar(x):
...     return x + 10
... 
>>> func_dict = {f.__name__:f for f in (foo, bar)}
>>> func_dict["foo"](10)
10
Sign up to request clarification or add additional context in comments.

Comments

1

If the functions are in the local namespace, just remove the quotes:

fncs = [MyLinkedList, addAtHead, get, addAtTail]
args = [[], [8], [1], [81]]

If the 1st list must be strings, you can get the function objects with:

function_names = ["MyLinkedList", "addAtHead", "get", "addAtTail"]
functions = [locals()[fn] for fn in function_names]

If, that is, the functions are named in the local namespace.

2 Comments

What if the functions are a list of strings and I can't change that?
Updated getting functions from locals by name.

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.