[Tutor] List comp question

Eric Brunson brunson at brunson.com
Sat Nov 3 17:51:02 CET 2007


Ricardo Aráoz wrote:
> Kent Johnson wrote:
>   
>> I am building a list like this:
>>
>>      tree = []
>>      for top in tops:
>>          l2 = level2(top)
>>          if l2:
>>              tree.append((top, l2))
>>
>> I would really like to turn this into a list comprehension:
>>
>> tree = [ (top, level2(top)) for top in tops if level2(top) ]
>>
>> but the call to level2() is expensive enough that I don't want to repeat 
>> it. Is there any way to do this or am I stuck with the (IMO ugly) loop form?
>>
>>     
>
> Just playing around here, but would this work and be better????
>
> tree = [ pair for pair in [ (top, level2(top)) for top in tops ]
>                           if pair[1] ]
>
>   

I came up with something very similar:

tops = [1,2,3,4,5]

def level2(n):
    m = n ** 2
    if m%2:
        return m
    else:
        return False

tree = [ (x, y) for x, y in [ ( x, level2(x) ) for x in tops ] if y ]
print tree
[(1, 1), (3, 9), (5, 25)]


But, now I would debate conciseness vs. readability and 
maintainability.  Will someone understand what's going on if they have 
to read it?  Will you remember what it does in six months when you're 
maintaining it?

Still, an interesting academic exercise.  :-)

e.

> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



More information about the Tutor mailing list