[Tutor] stumped by what looks like recursive list comprehension

Jim Mooney cybervigilante at gmail.com
Sun May 5 18:56:22 CEST 2013


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]

--
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.”


More information about the Tutor mailing list