C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: There are two ways to specify a generator. With the yield-keyword, we encapsulate a looping mechanism into a method.
Tip 2: With an expression, we use the for-keyword to specify simpler generators. These have less power.
Info: The yield statement can return an expression, not just a variable. Try changing "yield a" to "yield a + 1".
Also: The yield pattern here is the more powerful form. It can filter and transform elements.
Python program that uses yield
def odds(arg):
# Yield odd elements in the iterable.
for a in arg:
if a % 2 != 0:
yield a
# An input list.
items = [100, 101, 102, 103, 104, 105]
# Display all odd items.
for item in odds(items):
print(item)
# Print copied list.
copy = list(odds(items))
print(copy)
Output
101
103
105
[101, 103, 105]
Info: The expression "A" for "B" in "C" uses the generator expression syntax form.
First part: The first part, "A," is the result expression. We can use any expression we want.
Second part: The second, "B," is the element we are acting upon within the collection "C."
Python program that uses generator expression
# Example integers.
items = [100, 10, 1]
# Use generator expression.
multiplied = list(x * 2 for x in items)
print(multiplied)
Output
[200, 20, 2]
And: I found that a list comprehension was faster in both implementations I tried, Python and PyPy.
So: Often a list comprehension is faster despite the increased memory usage that may occur (according to the Python documentation).
Quote: Generator expressions... tend to be more memory friendly than equivalent list comprehensions.
Classes, Generator Expressions: python.orgPython program that benchmarks generator
import time
data = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(time.time())
# Version 1: generator.
i = 0
while i < 1000000:
double = list(x * 2 for x in data)
i += 1
print(time.time())
# Version 2: list comprehension.
i = 0
while i < 1000000:
double = [x * 2 for x in data]
i += 1
print(time.time())
Output
1404138028.766
1404138031.806 Generator: 3.04 s [Python 3.3]
1404138033.569 List comprehension: 1.76 s
1404137810.806
1404137811.086 Generator: 0.28 s [PyPy 2.3.1]
1404137811.287 List comprehension: 0.20 s
And: Imperative programming is where you specify individual statements on lines. It often involves traditional loops.
WhileNote: Thanks to Kimi Arthur for reporting an invalid benchmark result on a previous version of this page.