List comprehension vs generator expression memory allocation

candide candide at free.invalid
Sun Sep 20 15:35:44 CEST 2009


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

the function allows access to :

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]?






More information about the Python-list mailing list