Search code examples
pythonfunctionargumentsargument-passing

Passing *arg arguments from list


I'm in a situation when I have to call one function foo:

def foo(arg1,arg2,*args):
    pass

The problem is that I have the *args arguments stored during computing as a list.

Like this:

a = 'arg1'
b = 'arg2'
list_of_args = ['arg3','arg4','arg5']  

How can I call the function foo with this arguments to be like:

foo('arg1','arg2','arg3','arg4','arg5')

I could do this:

foo(a,b,list_of_args[0],list_of_args[1],list_of_args[2])

but it does not solve this problem because length of list_of_args depends on a situation so it could be:

foo(a,b,list_of_args[0],list_of_args[1],list_of_args[2],list_of_args[3],...)

Solution

  • Simply unpack the list with *:

    a = 'arg1'
    b = 'arg2'
    list_of_args = ['arg3','arg4','arg5']
    
    foo(a, b, *list_of_args)
    

    From the docs:

    If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from this iterable are treated as if they were additional positional arguments