The typing module has List for this purpose

from typing import List

def f(param: List[str]):
    pass
Answer from Iain Shelvington on Stack Overflow
🌐
W3Schools
w3schools.com › python › gloss_python_function_passing_list.asp
Python Passing a List as an Argument
Remove List Duplicates Reverse ... Training ... You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function....
Discussions

How to pass list of string as function argument in python? - Stack Overflow
I'm having a list of string and i need to pass it to function as a parameter. More on stackoverflow.com
🌐 stackoverflow.com
August 24, 2020
passing a list as function arguments
def fx(a,b): return a * b f = {'a': 2, 'b': 3} print(fx(**f)) More on reddit.com
🌐 r/learnpython
7
2
May 13, 2021
python - Create a function with two parameters: a list and a string, where the string has the following values - Code Review Stack Exchange
I tried so many things to do this task. I have no idea why doesn't it work. Please help! '''Create a function in Python that accepts two parameters. The first will be a list of numbers. The second More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
python - Defining a function whose arguments are given by a list of strings - Stack Overflow
I would like to define a function make_function that returns a new function. It takes as arguments a list arg_names of argument names for the new function and a function inner_func to be used in the More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 3
25

Parameters that can be either a thing or an iterable or things are a code smell. It’s even worse when the thing is a string, because a string is an iterable, and even a sequence (so your test for isinstance(names, Iterable) would do the wrong thing).

The Python stdlib does have a few such cases—most infamously, str.__mod__—but most of those err in the other direction, explicitly requiring a tuple rather than any iterable, and most of them are considered to be mistakes, or at least things that wouldn’t be added to the language today. Sometimes it is still the best answer, but the smell should make you think before doing it.

I don’t know exactly what your use case is, but I suspect this will be a lot nicer:

def spam(*names):
    namestr = ','.join(names)
    dostuff(namestr)

Now the user can call it like this:

spam('eggs')
spam('eggs', 'cheese', 'beans')

Or, if they happen to have a list, it’s still easy:

spam(*ingredients)

If that’s not appropriate, another option is keywords, maybe even keyword-only params:

def spam(*, name=None, names=None):
    if name and names:
        raise TypeError('Not both!')
    if not names: names = [name]

But if the best design really is a string or a (non-string) iterable of strings, or a string or a tuple of strings, the standard way to do that is type switching. It may look a bit ugly, but it calls attention to the fact that you’re doing exactly what you’re doing, and it does it in the most idiomatic way.

def spam(names):
    if isinstance(names, str):
        names = [names]
    dostuff(names)
2 of 3
2

Using isinstance() to identify the type of input may provide a solution:

def generate_names(input_term):
    output_list = []
    if isinstance(input_term,str):
        output_list.append(','.join(input_term.split()))
    elif isinstance(input_term,list):
        output_list.append(','.join(input_term))
    else:
        print('Please provide a string or a list.')
    return(output_list)

This will allow you to input list, string of a single name, as well as string containing several names(separated by space):

name = 'Eric'
name1 = 'Alice John'
namelist = ['Alice', 'Elsa', 'George']

Apply this function:

print(generate_names(name))
print(generate_names(name1))
print(generate_names(namelist))

Get:

['Eric']

['Alice,John']

['Alice,Elsa,George']

🌐
Note.nkmk.me
note.nkmk.me › home › python
Expand and Pass a List and Dictionary As Arguments in Python | note.nkmk.me
August 19, 2023 - In Python, you can expand a list, tuple, and dictionary (dict) and pass their elements as arguments by prefixing a list or tuple with an asterisk (*), and prefixing a dictionary with two asterisks (**) when calling functions.
🌐
Stack Overflow
stackoverflow.com › questions › 63556999 › how-to-pass-list-of-string-as-function-argument-in-python
How to pass list of string as function argument in python? - Stack Overflow
August 24, 2020 - I'm having a list of string and i need to pass it to function as a parameter. a_list = ['apple-banana','brinjal-carrot','cucumber'] function_call = fruit(a_list) def fruit(a_list): print("...
🌐
Stack Exchange
codereview.stackexchange.com › questions › 280704 › create-a-function-with-two-parameters-a-list-and-a-string-where-the-string-has
python - Create a function with two parameters: a list and a string, where the string has the following values - Code Review Stack Exchange
Replace all the print(...) in your function code with return .... And your *args parameter should just be args. \$\endgroup\$ ... args collects all positional arguments, str then becomes a keyword only argument. Since you pass the values as a single list instead of multiple single values you don't even need the *
Top answer
1 of 1
1

Perhaps exec is actually the best approach. eval/exec are usually not recommended if the input string is arbitrary/untrusted. However, when the code string which is eventually passed to the compiler was also generated by you, and not directly supplied by user, then it can be fine. There are some stdlib examples using this approach: namedtuple uses eval and dataclass uses exec, nobody has figured out how to exploit them (yet).

Now, I think that in your case it's fairly easy to do a safe code generation + exec simply by verifying that the args_names passed in is truly a list of arg names, and not some arbitrary Python code.

from textwrap import dedent
from typing import List, Callable

def make_function(args_names: List[str], inner_func: Callable):

    for arg_name in args_names:
        if not arg_name.isidentifier():
            raise Exception(f"Invalid arg name: {arg_name}")

    args = ', '.join(args_names)

    code_str = dedent(f"""\
        def outer_func({args}):
            return inner_func({args}) + 5
    """)

    scope = {"inner_func": inner_func}
    exec(code_str, scope)
    return scope["outer_func"]

Demo:

>>> def orig(a, b):
...     return a + b + 1
... 
>>> func = make_function(args_names=["foo", "bar"], inner_func=orig)
>>> func(2, 3)
11
>>> func(foo=2, bar=3)
11
>>> func(foo=2, bar=3, baz=4)
TypeError: outer_func() got an unexpected keyword argument 'baz'
>>> func(foo=2)
TypeError: outer_func() missing 1 required positional argument: 'bar'

As desired, it continues to work even when a local reference to the inner_func is no longer available, since we made sure the reference was available during code gen:

>>> del orig
>>> func(foo=2, bar=3)
11

Nefarious "argument names" are not allowed:

>>> make_function(["foo", "bar", "__import__('os')"], orig)
Exception: Invalid arg name: __import__('os')

For an approach without using code generation, it is also possible to instantiate types.FunctionType directly. To do this you need to pass it a types.CodeType instance, which are pretty difficult to create manually. These are public/documented, but the docstring for the code type even tries to scare you away:

>>> ((lambda: None).__code__.__doc__)
'Create a code object.  Not for the faint of heart.'

If you want to attempt it regardless, see How to create a code object in python? but I think you'll find that using eval, exec or compile is more convincing.

Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 66700976 › how-can-i-make-a-python-list-of-strings-to-be-read-as-arguments-of-a-python-func
How can I make a python list of strings to be read as arguments of a python function? [remake] - Stack Overflow
You say the arguments to your function are bools, but then you say you want to pass a list of strings as arguments to the function. A little more code with your intended result would be helpful here. ... @HenriChab I don't think that's what he's after. As far as I understand his question, he wants the strings in the list to be the names of variables of type boolean. ... Your request is unclear. You claim that you have an argument with a name that is a tuple of three strings; this is not legal Python.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-get-list-of-parameters-name-from-a-function-in-python
How to get list of parameters name from a function in Python? - GeeksforGeeks
March 8, 2025 - The task of getting a list of parameter names from a function in Python involves extracting the function's arguments using different techniques. These methods allow retrieving parameter names efficiently, whether from bytecode, introspection or source code analysis.
🌐
Python
docs.python.org › 3 › c-api › arg.html
Parsing arguments and building values — Python 3.14.3 documentation
Identical to PyArg_ParseTuple(), except that it accepts a va_list rather than a variable number of arguments. int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *const *keywords, ...)¶ · Part of the Stable ABI. Parse the parameters of a function that takes both positional and keyword parameters into local variables. The keywords argument is a NULL-terminated array of keyword parameter names specified as null-terminated ASCII or UTF-8 encoded C strings.
🌐
W3Schools
w3schools.com › python › python_arguments.asp
Python Function Arguments
You can send any data type as an argument to a function (string, number, list, dictionary, etc.).
🌐
Python documentation
docs.python.org › 3 › library › typing.html
typing — Support for type hints
February 24, 2026 - The argument list must be a list of types, a ParamSpec, Concatenate, or an ellipsis (...). The return type must be a single type. If a literal ellipsis ... is given as the argument list, it indicates that a callable with any arbitrary parameter ...
🌐
Sling Academy
slingacademy.com › article › python-passing-a-list-to-a-function-as-multiple-arguments
Python: Passing a List to a Function as Multiple Arguments - Sling Academy
def process_data(*args, **kwargs): # Process individual arguments for arg in args: print("Processing argument:", arg) # Process keyword arguments for key, value in kwargs.items(): print("Processing keyword argument:", key, "=", value) # Create a list and dictionary my_list = [1, 2, 3] my_dict = {"name": "Frienzied Flame", "age": 1000} # Pass the list and dictionary as multiple arguments to the function process_data(*my_list, **my_dict) ... Processing argument: 1 Processing argument: 2 Processing argument: 3 Processing keyword argument: name = Frienzied Flame Processing keyword argument: age = 1000 · That’s it. Happy coding! Next Article: Python: Generate a Dummy List with N Random Elements
🌐
i2tutorials
i2tutorials.com › home › python tutorial › python – functions with argument lists
Python - Functions with Argument Lists | i2tutorials
May 2, 2020 - In Python, Arguments in a function ... is treated as the same data type.If we give List as an argument to the function, it will consider the argument as List even if it is inside the function....
Top answer
1 of 6
296

To expand a little on the other answers:

In the line:

def wrapper(func, *args):

The * next to args means "take the rest of the parameters given and put them in a list called args".

In the line:

    func(*args)

The * next to args here means "take this list called args and 'unwrap' it into the rest of the parameters.

So you can do the following:

def wrapper1(func, *args): # with star
    func(*args)

def wrapper2(func, args): # without star
    func(*args)

def func2(x, y, z):
    print x+y+z

wrapper1(func2, 1, 2, 3)
wrapper2(func2, [1, 2, 3])

In wrapper2, the list is passed explicitly, but in both wrappers args contains the list [1,2,3].

2 of 6
28

The simpliest way to wrap a function

    func(*args, **kwargs)

... is to manually write a wrapper that would call func() inside itself:

    def wrapper(*args, **kwargs):
        # do something before
        try:
            return func(*a, **kwargs)
        finally:
            # do something after

In Python function is an object, so you can pass it's name as an argument of another function and return it. You can also write a wrapper generator for any function anyFunc():

    def wrapperGenerator(anyFunc, *args, **kwargs):
        def wrapper(*args, **kwargs):
            try:
                # do something before
                return anyFunc(*args, **kwargs)
            finally:
                #do something after
        return wrapper

Please also note that in Python when you don't know or don't want to name all the arguments of a function, you can refer to a tuple of arguments, which is denoted by its name, preceded by an asterisk in the parentheses after the function name:

    *args

For example you can define a function that would take any number of arguments:

    def testFunc(*args):
        print args    # prints the tuple of arguments

Python provides for even further manipulation on function arguments. You can allow a function to take keyword arguments. Within the function body the keyword arguments are held in a dictionary. In the parentheses after the function name this dictionary is denoted by two asterisks followed by the name of the dictionary:

    **kwargs

A similar example that prints the keyword arguments dictionary:

    def testFunc(**kwargs):
        print kwargs    # prints the dictionary of keyword arguments
🌐
Runestone Academy
runestone.academy › ns › books › published › thinkcspy › Lists › UsingListsasParameters.html
10.19. Using Lists as Parameters — How to Think like a Computer Scientist: Interactive Edition
Functions which take lists as arguments and change them during execution are called modifiers and the changes they make are called side effects. Passing a list as an argument actually passes a reference to the list, not a copy of the list. Since lists are mutable, changes made to the elements ...
🌐
Studytonight
studytonight.com › python-howtos › pass-a-list-to-a-function-to-act-as-multiple-arguments
Pass a List to a Function to act as Multiple Arguments - Studytonight
February 16, 2021 - In Python, functions can take either no arguments, a single argument, or more than one argument. We can pass a string, integers, lists, tuples, a dictionary etc. as function arguments during a function call. The function accepts them in the same format and returns the desired output. Now, we want to pass a list that contains multiple elements and these elements act as multiple arguments of a function.