Best way to convert a list into function call arguments?

B

bwooster47

I'm a newcomer to python - what is the best way to convert a list into
a function call agruments?

For example:

list = (2005, 5, 5)

date = datetime.date( list )
fails with:
TypeError: function takes exactly 3 arguments (1 given)

I assumed that since Python allows multiple assignments per statement,
such as
a, b, c = list
the date call above should work...

So, what is the best way to call date?
This works, but looks clunky:
date = datetime.date( list[0], list[1], list[2 )

Thanks!
 
J

Jeff Epler

Your question is answered in the tutorial:
http://docs.python.org/tut/node6.html#SECTION006740000000000000000

4.7.4 Unpacking Argument Lists

The reverse situation occurs when the arguments are already in a list or
tuple but need to be unpacked for a function call requiring separate
positional arguments. For instance, the built-in range() function
expects separate start and stop arguments. If they are not available
separately, write the function call with the *-operator to unpack the
arguments out of a list or tuple:
range(3, 6) # normal call with separate arguments [3, 4, 5]
args = [3, 6]
range(*args) # call with arguments unpacked from a list
[3, 4, 5]

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD8DBQFCeh8rJd01MZaTXX0RAqr8AJ9/nowD4UUUP/M6utwbbj8K1mlcsgCdHwAJ
VRusJ/qFlp4eCcF/aU+ulLk=
=Kn0d
-----END PGP SIGNATURE-----
 
B

bruno modulix

I'm a newcomer to python - what is the best way to convert a list into
a function call agruments?

Jeff Epler already answered to the question. Now a couple of advices:
For example:

list = (2005, 5, 5)

1/ this is not a list, it's a tuple. A list would be [2005, 5, 5]. (BTW,
it's quite ok - and even better imho - to use a tuple here)

2/ using the word 'list' as identifier shadows the builtin function
'list'. This is allowed, but you may prefer to avoid doing so.

3/ also, using the word 'list' as an identifier here is a poor choice
from a semantic POV, since it convey useless (and in this case wrong)
informations about an implementation detail (the data structure type)
but says nothing about the intended use of the data. Something like
'the_date' would have been better IMHO.

My 2 cents
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top