5

I have a function that takes a variable amount of variables as arguments. How would I the contents of some_list in the example below to my myfunc2()

def myfunc1(*args):
    arguments = [i for i in args]
    #doing some processing with arguments...
    some_list = [1,2,3,4,5] # length of list depends on what was  passed as *args
    var = myfunc2(???)  

The only way I can think of is to pass a list or tuple to myfunc2() as argument, but maybe there is a more elegant solution so I don't have to rewrite myfunc2() and several other functions.

4
  • possible duplicate of Python: Can a variable number of arguments be passed to a function? Commented Apr 11, 2013 at 15:45
  • arguments = [i for i in args] this is not needed as args is this ... (you may need to make it a list instead of a tuple) Commented Apr 11, 2013 at 15:54
  • your edit really confuses what your question is? is it how to pass arguments to a function? Commented Apr 11, 2013 at 15:54
  • It sort of already is in the answers below, but you probably want var = myfunc2(*some_list). Commented Apr 11, 2013 at 16:00

3 Answers 3

7

args is a tuple. *args converts arg to a list of arguments. You define myfunc2 the same way as myfunc1:

def myfunc2(*args):
    pass

To pass arguments, you can either pass then one by one:

myfunc2(a, b, c)

of grouper with * operator:

newargs = (a, b, c)
myfunc2(*newargs)

or using a combination of both techniques:

newargs = (b, c)
myfunc2(a, *newargs)

The same apply for ** operator, which converts dict to list of named arguments.

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

1 Comment

Thanks, that helps to solve my problem. So, I basically just have to prepare a set of tuples and can also use something like *args for the second function call.
2

this is pretty widely available and easily googleable ... Im curious what you searched for that you couldnt find a solution

def myfunc1(*args):
    arguments = args
    some_other_args = [1,2,3,4]
    my_var = myfunc2(*some_other_args) #var is not an awesome variablename at all even in examples

2 Comments

I am sorry, I forgot to mention that *args for myfunc1 and myfunc2 are supposed to be different. e.g. myfunc1() takes "a", "b", "c", and myfunc2() should take something like 1,2,3,4,5
I updated the initial question, I hope it makes sense now. sorry for the confusion
0

how about:

myfunc(*arguments)

same goes with keyword arguments such as:

def myfunc(*args, **kwargs):
    # pass them to another, e.g. super
    another_func(*args, **kwargs)

Comments

Your Answer

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