[Tutor] stumped by what looks like recursive list comprehension

Zachary Ware zachary.ware+pytut at gmail.com
Sun May 5 19:23:52 CEST 2013


On Sun, May 5, 2013 at 11:56 AM, Jim Mooney <cybervigilante at gmail.com>
wrote:
> I looked up "list comprehension" after the last explanation and it's
> really cool. But the example below stumps me. I understand the second
> part, "primes =" but the first part, "noprimes =" baffles me since it
> swaps i and j back and forth in what looks like a circle ;')  Also,
> the other examples I looked at had a function of 'x' before the 'for,'
> and 'x' after, so they were easy to follow. But this example has 'j'
> as a function of 'i,' then 'i,' as a function of 'j' and has me dizzy.
>
> Could someone show this in normal, indented 'for' loops so I can see
> what 'for' goes where and how it works. I figure if I figure this one
> one I'll really comprehend list comprehension.
>
> # find nonprimes up to 50, then filter out what's left as primes
>
> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
> primes = [x for x in range(2, 50) if x not in noprimes]

The standard expansion of a list comprehension is as follows:

noprimes = [] # start with an empty list

for i in range(2,8):            # add a colon, a newline, and another
indention
    for j in range(i*2, 50, i): # level just before each 'for' and 'if'
        noprimes.append(j)    # everything before the first 'for' goes in
an
                              # append call on the empty list

primes = []

for x in range(2, 50):
    if x not in noprimes:
        primes.append(x)


Hope this helps,

Zach Ware


>
> --
> Jim Mooney
>
> “For anything that matters, the timing is never quite right, the
> resources are always a little short, and the people who affect the
> outcome are always ambivalent.”
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130505/17a908e7/attachment.html>


More information about the Tutor mailing list