arbitrary number of arguments in a function declaration

rbt rbt at athop1.ath.vt.edu
Sun Jan 2 14:28:14 EST 2005


Nick Coghlan wrote:
> rbt wrote:
> 
>> How do I set up a function so that it can take an arbitrary number of 
>> arguments? For example, I have a bunch of expenses which may grow or 
>> shrink depending on the client's circumstance and a function that sums 
>> them up... hard coding them is tedious. How might I make this dynamic 
>> so that it can handle any amount of expenses?
>>
>> def tot_expenses(self, e0, e1, e2, e3):
>>     pass
> 
> 
> The Python Tutorial is a wonderful thing. . .

But so is this list ;)
> 
> Anyway, you can either set up your function to take a proper list, and 
> then discover that the sum function already exists to add up the 
> contents of a list:
> 
> def tot_expenses(self, expenses):
>   self.total_expenses = sum(expenses)
> 
> Or, have the function take a variable number of arguments, and do the 
> same thing:
> 
> def tot_expenses(self, *args):
>   self.total_expenses = sum(args)
> 
> Cheers,
> Nick.
> 

Many thanks!



More information about the Python-list mailing list