One thing that I always loved about Python was its readability. As I got into it more and more, though, I frequently ran into things that seemed pretty cryptic; one of them was the use of * and **, especially in function calls. This message on the Python list explains things pretty clearly (assuming you're familiar with the python 'zip' function!).
Begin forwarded message:
> From: Christopher T King <squirrel (at) WPI .DOT EDU> > Date: June 30, 2004 4:29:23 PM EDT > To: python-list@python.org > Subject: Re: zip asterisk syntax > X-Spambayes-Classification: ham; 0.00 > > garett wrote: > >> Hello, I have been reading text processing in python and in the >> appendix >> the author describes: >>>>> sides = [(3, 4), (7, 11), (35, 8)] >>>>> zip(*zip(*sides)) >> >> what is this asterisk-list syntax called? Any suggestions for finding >> more >> information about it? Thanks. -Garett > > It's called the "extended function call" syntax. Basically what it > does > is take the items of a list and use them as arguments to a function. > Let's take the example above: > >>>> sides = [(3, 4), (7, 11), (35, 8)] >>>> zip(*zip(*sides)) > > is the same as: > >>>> zip(*zip((3,4),(7,11),(35,8))) > > zip() mangles its arguments in such a way that the above call is > equivalent to this: > >>>> zip(*[(3,7,35),(4,11,8)]) > > which is the same as: > >>>> zip((3,7,35),(4,11,8)) > > which evaluates to [(3,4),(7,11),(35,8)]. > > Back on topic, the dictionary equivalent of * is **; that is, ** takes > the > key-value pairs from a dictionary and uses them as arguments to a > function. * and ** must appear after other arguments to the function, > and > you may only have at most one each of * and **. > > There's another context other than function calls in which * and ** > can be > used, and that's function definitions: > >>> def(a,b=5,*c,**d): pass > > will pack any extra arguments (beyond a and b) into list c and > dictionary > d. > > For (very) detailed information, see > http://docs.python.org/ref/calls.html > and http://docs.python.org/ref/function.html. > > -- > http://mail.python.org/mailman/listinfo/python-list
___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/
©2004 Ed Leafe |