(Feb-02-2022, 07:29 PM)Frankduc Wrote: But they still use the key word "def" and without the "yield" there is no generator. One would think they could of created some kind of method or class to represent the Generators.Can make a generator and not using a function,bye making a
generator expression
.>>> squares = (n** 2 for n in range(5)) >>> squares <generator object <genexpr> at 0x0000019FB47C6510> >>> list(squares) [0, 1, 4, 9, 16]From outside of function there is also
Iterator
.>>> lst = [1, 2, 3] >>> it = iter(lst) >>> it <list_iterator object at 0x0000019FB48430A0> >>> next(it) 1 >>> next(it) 2 >>> next(it) 3 >>> list(it) >>> it = iter(lst) >>> it <list_iterator object at 0x0000019FB47AC040> >>> list(it) [1, 2, 3]So work it similar way,in fact so a
Generator
a subclass of Iterator
.The main strategy of this is Lazy Evaluation.
A evaluation strategy which delays the evaluation of an expression until it's value is
needed
,and also avoids repeated evaluations.
When moved from Python 2 to 3 was made a lot stuff was rewritten to use this strategy.
# Python 2.7 >>> range(5) [0, 1, 2, 3, 4] >>> zip(range(5), range(5)) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]Python 2 return a finish made list.
# Python 3.10 >>> range(5) range(0, 5) >>> list(range(5)) [0, 1, 2, 3, 4] >>> zip(range(5), range(5)) <zip object at 0x0000019FB41B27C0> >>> list(zip(range(5), range(5))) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]In Python 3 it's lazy evaluated,so have to
iterate
over it to get result or call list() or other function like sum().>>> sum(range(5)) 10