question about Z=[[x for y in range(1, 2) if AList[x]==y] for x in range(0,5)]

Chris Rebert clp2 at rebertia.com
Sun Feb 1 20:19:39 EST 2009


On Fri, Jan 30, 2009 at 5:33 PM, Vincent Davis <vincent at vincentdavis.net> wrote:
> Z=[[x for y in range(1,2) if AList[x]==y] for x in range(0,5)]
> I am not sure how to ask this but which "for" is looped first? I could
> test but was wondering if there was a nice explanation I could apply
> to future situations.

The outer one. Remember that you can always rewrite (a) list
comprehension(s) into (an) equivalent for-loop(s). In this case:
Z = []
for x in range(0,5):
    _tmp = []
    for y in range(1,2):
        if AList[x]==y:
            _tmp.append(x)
    Z.append(_tmp)

Or alternatively, imagine if the inner list comprehension was instead
a function call:

#assuming AList is a global var
def inner_list_comp(x):
    return [x for y in range(1,2) if AList[x]==y]

Z=[inner_list_comp(x) for x in range(0,5)]

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list