Python
/
Goodies
- 1 Language 9
-
Hello World
-
Variables
-
Functions
-
Conditional
-
Operators
-
While
-
Turtle
-
Script Mode
-
Debugging
- 2 Strings 6
-
Slice
-
Raw Strings
-
Regex
-
Validation
-
Config
-
Escape
- 3 Collections 5
-
Lists
-
Dictionaries
-
Efficiency
-
Tuples
-
References
- 4 Functions 5
-
Recursion
-
Factorial
-
Modulus
-
Reassignment
-
Approximate
- 5 Storage 8
-
Files
-
Databases
-
Pipes
-
With open
-
Shelve
-
Zip
-
Csv
-
Json
- 6 Class 4
-
Definition
-
Attributes
-
Functional
-
Methods
- 7 Goodies 5
-
Conditional Expression
-
List Comprehension
-
Generator
-
Named Tuple
-
Modules
- 8 Applications 5
-
Pythagora
-
Palindrome
-
Binary Search
-
Conway Game
-
Coin Flip
- 9 Scheduler 4
-
Time
-
Multithreading
-
Subprocess
-
Logging
- 10 Packages 2
-
Clipboard
-
Ocr
/
Generator
➟
➟
Last update: 19-11-2021
Generators
p330 ! Generators does not compute the values at once, it waits to be asked.
# A generator object knows how to iterate a sequence of values.
#
# Unlike list, ...
# it does not compute the values at once, ...
# it waits to be asked.
#
# A generator expression are similar with list comprehesion,
# but with parantheses instead of square brakets
# Generator
g = (x**2 for x in range(3))
assert next(g) == 0
assert next(g) == 1
assert next(g) == 4
next(g) # StopIteration - Exception
# Populate a list using generator
# only once at a time
list = []
g = (x**2 for x in range(101010))
list.append(next(g))
list.append(next(g))
assert len(list) == 2
assert len(list) != 101010
# Populate a list using for loop
# automatically invokes __next__ generator
list = []
for x in range(101010): # __next__
list.append(x)
assert len(list) != 1
assert len(list) == 101010
Functions
Generators are often used with functions like sum, max, min.
# Generators are often used ...
# with functions like sum, max, min
y = sum(range(5)) # 0 + 1 + 2 + 3 + 4
assert y == 10
assert y != 15
y = sum(x**2 for x in range(5)) # generator
# 0 + 2 + 4 + 8 + 16
assert y == 30
assert y != 10
y = max([1, 10, 2, 3])
assert y == 10
assert y != 3
y = max(x/2 for x in [10, 50, 20, 30])
assert y == 25.0
assert y != 15.0
➥ Questions github Goodies