Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a list to a function to act as multiple arguments

People also ask

Can a list be passed as an argument to a function?

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.

How do you provide a function multiple arguments?

The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we don't know how many arguments will be sent to the function.

How do you pass list elements as parameters in Python?

In Python, you can unpack list , tuple , dict (dictionary) and pass its elements to function as arguments by adding * to list or tuple and ** to dictionary when calling function.


function_that_needs_strings(*my_list) # works!

You can read all about it here.


Yes, you can use the *args (splat) syntax:

function_that_needs_strings(*my_list)

where my_list can be any iterable; Python will loop over the given object and use each element as a separate argument to the function.

See the call expression documentation.

There is a keyword-parameter equivalent as well, using two stars:

kwargs = {'foo': 'bar', 'spam': 'ham'}
f(**kwargs)

and there is equivalent syntax for specifying catch-all arguments in a function signature:

def func(*args, **kw):
    # args now holds positional arguments, kw keyword arguments

Since Python 3.5 you can unpack unlimited amount of lists.

PEP 448 - Additional Unpacking Generalizations

So this will work:

a = ['1', '2', '3', '4']
b = ['5', '6']
function_that_needs_strings(*a, *b)