Multiple arguments: how do you handle them 'nicely'?

Michael Chermside mcherm at destiny.com
Fri Aug 9 18:00:55 CEST 2002


>     def f(*args):
>         for i in args:
>             print i
> 
> Now for a sequence of discrete arguments like:
>>>> f(1,2,3)
> 1
> 2
> 3
>>>>
> 
> But for a list or tuple (which might be the result of another function's
> return value)
>>>> f( [1,2,3] )
> [1,2,3]
                           [...]
> I would prefer that f() behave the same way for either a list or tuple,
> or a comma separated
> series of arguments.

What you are asking for is really quite unusual in Python (although it 
makes perfect sense in perl, which is probably where you learned the idiom).

You generally do NOT want f(a,b,c) and f([a,b,c]) to do the same thing 
in Python. Because if they did, it would prevent you (or at least 
confuse you dreadfully) when you tried to invoke f([a,b,c], d, e). In 
perl, the arguments are treated as a list, and any lists in the 
arguments are just a few more arguments. This makes it more difficult to 
operate on LISTS THEMSELVES by passing them as single arguments.

So my first advise is for you to try learning the Python idiom. You'll 
find it works much better for you. If you have myList=[a,b,c] and you 
want to invoke f(a,b,c), then instead of typing "f(myList)" (which means 
to pass 1 argument, which is the list myList), you should type 
"f(*myList)" (that extra * means that the list contains the values 
instead of BEING one of the values).

-- Michael Chermside

PS: If you really do know what you're doing and still want to do this, 
then I think others have already provided sample code that would allow it.





More information about the Python-list mailing list