unpacking function argument

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

It’s called argument unpacking and is written as:

func1(*func2(...))

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x