Function parameter passing: Have list, need individual args

This is the place for queries that don't fit in any of the other categories.

Function parameter passing: Have list, need individual args

Postby rovf » Wed Mar 19, 2014 4:48 pm

Let's assume I have two functions with the following properties:

Code: Select all
def give():
  ''' returns a list of two items '''
  return ('foo','bar')
def take(x,y,z):
  return x+y+z # just an example


and I want to use these functions in the following way:

Code: Select all
(temp1,temp2)=give()
result=take('baz',temp1,temp2)


My question: Can I write this in a compact way, without the need of temporary variables, and assuming that I must not modify the interface of the take-function?

Of course,
Code: Select all
take('baz',give())
doesn't work, because this would assign the whole list to the y-argument.

If I have this pattern frequently, I can write a wrapper function around take, i.e.

Code: Select all
def takel(x,l):
  return take(x,l[0],l[1])


but I wonder whether Python has some intrinsic mechanism of distributing the elements of a tuple over the formal arguments of a function, maybe in the spirit of how functions with a variable number of arguments are handled...
rovf
 
Posts: 25
Joined: Fri Aug 16, 2013 4:35 pm

Re: Function parameter passing: Have list, need individual a

Postby metulburr » Wed Mar 19, 2014 5:19 pm

Code: Select all
def give():
  ''' returns a list of two items '''
  return ('foo','bar')

that is returning a tuple, not a list

unpack the tuple arguments in the function call
Code: Select all
take('baz',*give())


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.).
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1469
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY


Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot], Google [Bot], W3C [Linkcheck] and 4 guests