* operator--as in *args?

Alex Martelli aleax at mac.com
Mon Mar 19 02:21:41 CET 2007


7stud <bbxx789_05ss at yahoo.com> wrote:

> On Mar 18, 3:40 pm, "Dustan" <DustanGro... at gmail.com> wrote:
> > For example:
> > aFunction(*(1,2,3))
> > is equivalent to:
> > aFunction(1,2,3)
> >
> 
> That's the context I've seen it in, but written like this:
> 
> someFunc(*args)
> 
> I played around with it a little bit, and it appears the * operator
> unpacks a list, tuple, or dictionary so that each element of the
> container gets assigned to a different parameter variable.  Although
> with a dictionary, only the keys appear to be assigned to the
> parameter variables, e.g.:
> 
> def g(a,b,c):
>         print a, b, c
> 
> dict = {"x":10, "y":20, "z":30}
> g(*dict)
> 
> Is that right?

As far as it goes, yes.  More generally, with any iterable x, the *x
construct in function call will pass as positional arguments exactly
those items which (e.g.) would be printed by the loop:
    for item in x: print x

[[this applies to iterators, generators, genexps, and any other iterable
you may care to name -- not just lists, tuples, dicts, but also sets,
files open for reading [the items are the lines], etc, etc]].


Alex



More information about the Python-list mailing list