arbitrary number of arguments in a function declaration

Nick Coghlan ncoghlan at iinet.net.au
Sun Jan 2 14:26:39 EST 2005


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. . .

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.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list