[Tutor] How is the return statement working in this function?

Brian van den Broek brian.van.den.broek at gmail.com
Fri Apr 6 03:29:30 CEST 2012


On 6 Apr 2012 02:43, "Greg Christian" <glchristian at comcast.net> wrote:
>
> I am just wondering if anyone can explain how the return statement in
this function is working (the code is from activestate.com)? Where does x
come from – it is not initialized anywhere else and then just appears in
the return statement. Any help would be appreciated.
>
>
> def primes(n):
>     """Prime number generator up to n - (generates a list)"""
>     ## {{{ http://code.activestate.com/recipes/366178/ (r5)
>     if n == 2: return [2]
>     elif n < 2: return []
>     s = range(3, n + 1, 2)

<snip>

>     return [2]+[x for x in s if x]

Hi Greg,

That it appears is a return isn't relevant. The bit '[x for x in s if x]'
is a list comprehension. They build lists in an economical way. This one is
equivalent to:

result = []
for x in s:
    if x:
        result.append(x)

Informally, you can think of the 'for x' as working kind of like "for every
student" when a teacher reminds him or herself to praise students by
repeating softly "for every student in my class praise that student".

HTH,

Brian vdB
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120406/f956247f/attachment.html>


More information about the Tutor mailing list