15

if a function takes n number of arguments, and there is another function that returns a sequence with n number of items(or I have a sequence with n number of items), is there a way to 'map' these two functions(or make the first function take a sequence of n number of items as input and return result) I don't want (and maybe can't in some occasions) to edit the function myself and change its arguments parameters and return value types.

i.e)

def func1(x, y, z):
    return x+y+z

def func2(w):
    return [i for i in range(w,w+3)]

cant func1(func2( ... )) in this case.

thkang
  • 10,747
  • 12
  • 62
  • 81

2 Answers2

18

You are looking for the *args argument syntax:

>>> def foo(bar, baz, spam):
...     print bar, baz, spam
...
>>> arguments = [1, 2, 3]
>>> foo(*arguments)
1, 2, 3

When passing arguments to a callable, any expression preceded by a * asterix, is interpreted as a sequence of positional arguments, and expanded to be passed on as separate arguments to the called object (function, method, etc.).

For your example that would be:

func1(*func2(...))

There is a keyword equivalent using ** double asterixes (takes a mapping), and you can use the same syntax in function signatures too.

See the documentation on call expressions, and for the function signature mirror syntax, the documentation on function definitions.

trss
  • 913
  • 1
  • 17
  • 33
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
12

It's called argument unpacking and is written as:

func1(*func2(...))

Refer: https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists

trss
  • 913
  • 1
  • 17
  • 33
Jon Clements
  • 132,101
  • 31
  • 237
  • 267