[Tutor] List comp question

Ricardo Aráoz ricaraoz at gmail.com
Sat Nov 3 00:56:46 CET 2007


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




More information about the Tutor mailing list