# List comprehension vs generator expression memory allocation

Sun Sep 20 15:50:34 CEST 2009

On 20 Sep, 14:35, candide <cand... at free.invalid> wrote:
> Let's code a function allowing access to the multiples of a given
> integer (say m) in the range from a to b where a and b are two given
> integers. For instance, with data input
>
> a,b,m=17, 42, 5
>
>
> 20 25 30 35 40
>
> Each of the following two functions mult1() and mult2() solves the
> question :
>
> # -----------------------------------------
> def mult1(a,b,m):
>     return (x for x in range(a,b)[(m-a%m)%m:b:m])
>
> def mult2(a,b,m):
>     return range(a,b)[(m-a%m)%m:b:m]
> # -----------------------------------------
>
> mult2() function returns a list and obviously mult2() needs Python to
> allocate memory for this list. What I was wondering is if the same might
> be said about mult1(). More precisely, does Python allocate memory for
> the whole target list range(a,b)[m-a%m:b:m]?

Yes - range always creates a list (in the 2.x series) -- mult1 creates
a list, then returns a generator, so list(mult1(a,b,m)) is identical
to mult2(a,b,m).

Jon.