A nerd pretending to be a software engineer.

Python Generator Expression

Written on

Continuing the last post, another thing i would like to note is the generator expression in python. The function is almost the same as the list comprehension, but instead of processing the whole data structures at once, it performs the works one at a time. This would mean less memory usage and performance when dealing with a massive amount of data. To use it, just replace the square brackets on list comprehension with parentheses.

evens = (for x in range(10000) if x%2==0)
for x in evens:
    print evens

# more example, this can apply to list comprehension as well
# generate a tuple of possible combinations of odd and even number in the range
permutation = ((x,y) for x in range(5) if x%2==0 for y in range(5,10) if y%2!=0)

This entry is posted in 2012.

comments powered by Disqus