3

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.

  • possible duplicate of [Python: Can a variable number of arguments be passed to a function?](http://stackoverflow.com/questions/919680/python-can-a-variable-number-of-arguments-be-passed-to-a-function) – karthikr Apr 11 '13 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) – Joran Beasley Apr 11 '13 at 15:54
  • your edit really confuses what your question is? is it how to pass arguments to a function? – Joran Beasley Apr 11 '13 at 15:54
  • It sort of already is in the answers below, but you probably want `var = myfunc2(*some_list)`. – Jaime Apr 11 '13 at 16:00

3 Answers3

5

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.

Charles Brunet
  • 21,797
  • 24
  • 83
  • 124
  • 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. –  Apr 11 '13 at 15:59
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
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • 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 –  Apr 11 '13 at 15:48
  • I updated the initial question, I hope it makes sense now. sorry for the confusion –  Apr 11 '13 at 15:55
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)
kirpit
  • 4,419
  • 1
  • 30
  • 32