Python
/
Goodies
- 1 Language 9
-
Hello World S
-
Variables S
-
Functions S
-
Conditional A S
-
Operators S
-
While S
-
Turtle S
-
Script Mode S
-
Debugging S
- 2 Strings 7
-
Slice S
-
Raw Strings S
-
Regex A S
-
Validation S
-
Config S
-
Security S
-
Encrypt A S
- 3 Collections 5
-
Lists S
-
Dictionaries S
-
Efficiency S
-
Tuples S
-
References S
- 4 Functions 5
-
Recursion S
-
Factorial S
-
Modulus S
-
Reassignment S
-
Approximate S
- 5 Storage 8
-
Files S
-
Databases S
-
Pipes S
-
With open S
-
Shelve A S
-
Zip S
-
Csv S
-
Json S
- 6 Class 4
-
Definition S
-
Attributes S
-
Functional S
-
Methods S
- 7 Goodies 5
-
Conditional Expression S
-
List Comprehension S
-
Generator S
-
Named Tuple S
-
Modules S
- 8 Applications 5
-
Pythagora A S
-
Palindrome A S
-
Binary Search A S
-
Conway Game A S
-
Coin Flip A S
- 9 Scheduler 4
-
Time S
-
Multithreading A S
-
Subprocess S
-
Logging S
- 10 Packages 6
-
Clipboard A S
-
Ocr A S
-
Socket S
-
Image S
-
Virtualenv S
-
Jupyter S
S
R
Q
Python Goodies Generator
Does not compute values at once ... waits to be asked Similar with list comprehension ... parantheses instead of square brakets g = (x**2 for x in range(3)) next(g) == 0 next(g) == 1 next(g) == 4
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
Last update: 90 days ago