[Tutor] Passing values of a list as arguments
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Fri, 23 Nov 2001 02:19:32 -0800 (PST)
On Fri, 23 Nov 2001, lonetwin wrote:
> Hi all,
> I just can't figure out to do this:
> ====================
> def somefunc(arg1, arg2=None)
> if not arg2:
> arg2 = someOtherValue
> ....
> ....
> ....
>
> if __name__ == '__main__':
> somefunc(sys.argv)
> ====================
> I hope you see my problem, I want to pass the values of sys.argv (or any
> list for that matter) as arguments to somefunction, without resorting to
> something like:
> ====================
> def somefunc(list)
> arg1, arg2 = list[1], list[2] or someOtherValue
> ....
> ....
> ....
>
> if __name__ == '__main__':
> somefunc(sys.argv)
> ====================
>
> ....which I think is kinda ugly for more that 3 arg values (python
> sure does makes one *very* picky :))
I see! Yes, you can do this by using apply(). Here's a toy example:
###
>>> def add(x, y=None):
... if y == None: y = 0
... return x + y
...
>>> apply(add, [1, 2])
3
>>> apply(add, [1])
1
###
apply() is specifically designed for this kind of stuff, where the second
argument is a list that will be used for the arguments of a function. You
can see more about apply() here:
http://python.org/doc/current/lib/built-in-funcs.html
Python has an alterative way of doing this as of 2.0, by using starred
notation. Take a look at:
http://python.org/2.0/new-python.html#SECTION0001010000000000000000
for an explanation about it.
Good luck!