Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Generator expression in Python

📅 2012-May-01 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ expression, generator, python ⬩ 📚 Archive

A generator expression is very similar to list comprehension in Python. The advantage of the generator expression over list comprehension is that the resulting list of items is not actually created and filled in the former. Instead, the expression returns a generator object. On each call of the next() on this object, it returns the next item in the sequence. When the end of the sequence is reached, a StopIteration exception is thrown by next().

# List comprehension
a = [ i for i in range( 3 ) ]

# Generator expression
b = ( i for i in range( 3 ) )
next( b ) # 0
next( b ) # 1
next( b ) # 2
next( b ) # StopIteration

A generator expression is useful to iterate through a very large or infinite sequence, since a list that large does not actually need to be created.

A generator object can be used in a for loop for iterating through its sequence easily without having to call next().

b = ( i for i in range( 3 ) )
for j in b:
    print( j )
# 0 1 2

Tried with: Python 3.2


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧