If you havent gone through previous post on list comprehension please do so .. As noted there, list comprehensions act on sequence and produce a list output which is fast and efficient.. But if this list is just an intermediate step in your python expression, use generator expressions.
Why ? It saves memory!!!
Instead of storing the resulted list, generators return only one item of the list at a time.
If you know list comprehensions , you can use the same syntax for generator expressions as well with a small difference that, list comprehensions use [] when generator expressions use ()
list comprehension example:
>>> [x for x in range(1,10) ]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
generator expression example
>>> (x for x in range(1,10) )
<generator object <genexpr> at 0x7fa5d0252eb0>
>>> y= (x for x in range(1,10) )
generator object have "next" method as shown below:
>>> y.next
<method-wrapper 'next' of generator object at 0x7fa5d01facd0>
so, we can even make use of "next()" to get next item:
>>> y.next()
1
>>> y.next()
2
>>> y.next()
3
>>> y.next()
4
>>> y.next()
5
>>> y.next()
6
>>> y.next()
7
>>> y.next()
8
>>> y.next()
9
If there are no more elements, it return "StopIteration" exception :
>>> y.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration