Variable arguments to a Python function
Sean Ross
frobozz_electric at hotmail.com
Thu May 29 00:59:18 EDT 2003
import operator
def product(*sequence):
return reduce(operator.mul, sequence)
>>> product(1,2,3)
6
or, for a more direct interpretation of the perl code
def all_of(*args):
result = 1
for i in args:
result *= i
return result
>>> all_of(1,2,3)
6
you cannot however do a direct translation, i.e., the following does not
work:
def all_of(*args):
result = 1
while args:
result *= args.pop()
return result
>>> all_of(1,2,3)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 4, in all_of
AttributeError: 'tuple' object has no attribute 'pop'
Because *args is a tuple, and tuples are immutable. But, you can do this (if
you want too)
def all_of(*args):
args = list(args)
result = 1
while args:
result *= args.pop()
return result
>>> all_of(1,2,3)
6
"Mahboob" <mahboob at bellsouth.net> wrote in message
news:HWfBa.231$zY5.27 at fe02.atl2.webusenet.com...
> How can I pass variable number of arguments to a Python function and
access
> them inside the function?
>
> In Perl, you could write
>
> sub all_of {
> my $result = 1;
> while ( @_) {
> $result *= shift;
> }
> return result;
> }
> (From Mastering Algorithms with Perl, pg 569)
> You can compute the product of any number of variables with the above
> function.
>
> Thanks,
> -- Mahboob
>
>
>
More information about the Python-list
mailing list