For loop extended syntax

George Sakkis gsakkis at rutgers.edu
Mon Mar 21 15:56:26 EST 2005


"Ron" <radam2 at tampabay.rr.com> wrote:

> How would this examples work?
>
> for x=5,y,z in (123),(4,5),(6,7,8,9)
>
> Would the x default over ride the first value?
> Should, the 4 element in the third tuple be dropped without an error?

It has already been clarified twice in the thread that the default values would be allowed *only in
the end*, exactly as default function arguments.

> A  general reusable function might be something like this:
>
> def formatlistofargs(arglist, nargs=1, defvalue=0):
>     returnvalues = []
>     for i in arglist:
>         ii = list(i)
>         while len(ii)<nargs:
>             ii.append(defvalue)
>         ii=ii[:nargs]
>         returnvalues.append(ii)
>     return returnvalues
>
> for x,y,z in formatlistofargs(((1,2,3),(3,4),(5,6,7,8)),3):
>     print x,y,z

Of course there are ways to have a function fill in the defaults, but syntactically I would find
"for (x,y,z=0) in (1,2,3), (4,5), (6,7,8): print x,y,z" more obvious and concise.

By the way, I don't think it's a good idea in general to drop the extra values implicitly, as you do
in your recipe, for the same reason that calling a function foo(x,y,z) as foo(1,2,3,4) is an error.
A generalization of the 'for .. in' syntax that would handle extra arguments the same way as
functions would be:

for (x,y,z=0,*rest) in (1,2,3), (3,4), (5,6,7,8):
     print x, y, z, rest

I'd love to see this in python one day; it is pretty obvious what it would do for anyone familiar
with function argument tuples.

George





More information about the Python-list mailing list