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

Dave Angel d at davea.name
Fri Apr 6 03:01:55 CEST 2012


On 04/05/2012 08:39 PM, Greg Christian 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)
>     mroot = n ** 0.5
>     half = (n + 1)/2 - 1
>     i = 0
>     m = 3
>     while m <= mroot:
>         if s[i]:
>             j = (m * m - 3)/2
>             s[j] = 0
>             while j < half:
>                 s[j] = 0
>                 j += m
>         i = i + 1
>         m = 2 * i + 3
>     return [2]+[x for x in s if x]
>

The expression [x for x in s if x] is called a list comprehension, and
it defines x as it needs it.   The results of that expression is a list,
which is concatenated to the end of the list [2], and the combined list
is returned.

For example, try the one-liner:


    print    [i for i in xrange(5)]



-- 

DaveA



More information about the Tutor mailing list