- What method(s) must iterables have?
- What method(s) must iterators have?
- What data type does
- What data type does
- Is a generator an iterable or an iterator?
- What keyword in the body of a function makes that function return a generator object?
- How is
- When you call
nexton a generator, the body starts executing at what line? At what line will it stop? At what line will it start the next time you call
- What happens when you call
liston an iterable or an iterator? What happens if you call it a second time on the same objects?
- Can you iterate through an iterable in a for loop? Can you iterate through an iterator in a for loop?
whatever type each element of the sequence is
yielddoes not close the frame.
yieldoutputs a value, and keeps the frame open until
execution starts at the first line of the body and stops after the line with
yieldis executed. when
nextis called again, execution picks up at the line right after the
yieldstatement (where it last left off) and stops after another
yieldexecution or if there are no more lines in the body.
when you call
liston an iterable or an iterator, Python calls
iteron it and then attempts to construct a list with the
StopIterationis reached, then returns the constructed list.
you can use both iterables and iterators in a for loop.
What would Python print?
The following classes define an iterable representing the sequence of multiples for any given number and the iterator that returns the next value in the sequence. The sequence goes up to 1000.
What will the following lines output?
>>> hundreds = Multiples(100)
>>> next(hundreds) TypeError: 'Multiples' object is not an iterator >>> next(iter(hundreds)) 100 >>> next(iter(hundreds)) 100 >>> i = iter(hundreds) >>> i is iter(hundreds) False >>> i is iter(i) True >>> next(i) 100 >>> next(i) 200 >>> list(hundreds) [100, 200, 300, 400, 500, 600, 700, 800, 900] >>> list(i) [300, 400, 500, 600, 700, 800, 900] >>> list(hundreds) [100, 200, 300, 400, 500, 600, 700, 800, 900] >>> list(i)  >>> for i in hundreds: ... print(i) 5
625 >>> for x in i: ... print(x)
__iter__ method always returns a *new instance* of
__iter__ simply returns itself. For iterables, calling
iter will reset the iterator, but since iterators just return themselves, they do not reset.
Fill in the following definition of a generator function which yields every number from
n and prints
'm was a factor' if the previous number,
m, was a factor of
n. See the doctests for an example.