The need to use *arg,**kwd

Sean DiZazzo half.italian at gmail.com
Tue Sep 16 03:43:58 EDT 2008


On Sep 15, 11:54 pm, "Marco Bizzarri" <marco.bizza... at gmail.com>
wrote:
> On Mon, Sep 15, 2008 at 11:51 PM, AON LAZIO <aonla... at gmail.com> wrote:
> > Hi, Pythoners.
> >        I'd like to know when it is necessary to use *arg or **kwd in the
> > program. And when it is 'ok' to use normal form of function argument?
> > Thanks in advance.
>
> > Aonlazio
>
> Sorry, Aonlazio, but which program? This is a fair generic question
> which needs a little more details to be answered.
>
> You are not required to use them. You can use them if problem can be
> easily solved with them. Which, of course leads to the questionof what
> your problem is ;)
>
> Regards
> Marco
> --
> Marco Bizzarrihttp://notenotturne.blogspot.com/http://iliveinpisa.blogspot.com/

Aonlazio,

*args and **kwargs are both a conveneince and for situations where the
function could take a variable number of arguments.

Take for example a sum function:

def sum(first, second):
    return first + second

This function can only take two arguments and return the result of the
two.  You can add more arguments to the function definition, but if
you want to make a generic sum function, it should be able to take as
many arguments as your user wants to throw at it.  In this case you
can use *args.  ie.

def sum(*args):
    total =0
    for arg in args:
        total += arg
    return total

**kwargs works the same way, but for keyword arguments.  I can't think
of a useful example...I tried. :)  I'm sure others will have good use
cases.

~Sean



More information about the Python-list mailing list