For loop extended syntax

Ron radam2 at tampabay.rr.com
Mon Mar 21 21:33:11 EST 2005


On Mon, 21 Mar 2005 15:56:26 -0500, "George Sakkis"
<gsakkis at rutgers.edu> wrote:


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

Was just asking if there should be other special general cases.  What
programmers want usually depend on the problem at hand. imho  :)

>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

I would probably do it this way myself:

def padlist(alist,length,pad):
    alist[length:]=[pad]*(length-len(alist))
    return alist

for xyz in [1,2,3],[3,4],[5,6,7]:
    x,y,z = padlist(xyz, 3, 0)
    print x,y,z

# or this if it's faster:
    
for x,y,z in [padlist(xyz,3,0) for xyz in [1,2,3],[3,4],[5,6,7]]:
    print x,y,z


Which isn't too different from what you are suggesting.  I think
someone may have already suggested using list comprehensions.

Ron









More information about the Python-list mailing list