Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Wednesday, May 2, 2012

List Comprehensions and Generator Expressions

In functional programming two basic but heavily used operations on iterators are "List Comprehensions" and "Generator Expressions". Let's take a look at what now exactly the difference is.
sentence= "What is the difference between list comprehensions and generator expressions"

word_listcomprehension = [word for word in sentence.split() if len(word) > 3]
print word_listcomprehension

word_generatorexpr = (word for word in sentence.split() if len(word) > 3)
print word_generatorexpr
print next(word_generatorexpr) #print first element
print next(word_generatorexpr) #print second element
print next(word_generatorexpr) #print third element

As you can see a listcomprehension typically returns a list while a generator expression returns a generator. This means that a generator computes values lazily only when they are requested. For very big or infinite iterators listcomprehensions are not useful and generators are the only way to handle this.
['What', 'difference', 'between', 'list', 'comprehensions', 'generator', 'expressions']
<generator object <genexpr> at 0xb754e1e4>
What
difference
between
]]>

It is even possible to write a generator function using the yield keyword.
def alphabet():
   "Return letters of alphabet"
   letters = "abcdefghijklmnopqrstuvwxyz"
   for letter in letters:
       yield letter  

letters_of_alphabet = alphabet()
print next(letters_of_alphabet)
print next(letters_of_alphabet)  


a
b 

No comments:

Post a Comment