In Python, a generator expression is a concise way to create an generator out of an iterable. A generator expression traverses an iterable, keeps certain values, evaluates an expression, and collects the values in a generator object. Putting list brackets around the generator expression converts the generator object to a list comprehension.
The syntax of a generator expression is:
(expression for elem in iterable if condition). The conditional is optional, and in some cases the parentheses are optional.
A generator expression executes as follows:
- traversal: for elem in iterable causes
elemto successively take on the value of each item in the iterable.
- filter: for each
elem, if condition passes, we go on to the expression.
- expression: expression is the value that is stored in the iterable
The generator object returned by the expression above is equivalent to
gen in the following code:
def gen(): for elem in iterable: if condition: yield expression gen = gen()
Example with all the components:
>>> result = (x * x for x in range(10) if x % 2 == 0) >>> result <generator object <genexpr> at 0x...> >>> list(result) # convert generator object to list [0, 4, 16, 36, 64]
Example without the conditional:
>>> [x * x for x in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Example with a list:
>>> broken_sentence = ["oppa", "gangnam", "style"] >>> [word + "op" for word in broken_sentence] ['oppaop', 'gangnamop', 'styleop']