For loop extended syntax

Ron radam2 at tampabay.rr.com
Mon Mar 21 09:16:25 EST 2005


On Sun, 20 Mar 2005 13:16:37 -0500, "George Sakkis"
<gsakkis at rutgers.edu> wrote:

>I'm sure there must have been a past thread about this topic but I don't know how to find it: How
>about extending the "for <X> in" syntax so that X can include default arguments ? This would be very
>useful for list/generator comprehensions, for example being able to write something like:
>
>[x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)]
>
>instead of the less elegant explicit loop version that has to check for the length of each sequence.
>What do you think ?
>
>George
>

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?


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


Ron




More information about the Python-list mailing list