Python generator, iteratable object, iterator difference and connection, python Generator
What is the relationship between generators, iteratable objects, and iterators?
Use a picture to summarize:
1. Generator
Definition Generator
Method 1:
// Unlike the list generator gen = [x * x for x in range (5)] gen = (x * x for x in range (5) print (gen) // Out: <generator object <genexpr> at 0x00000258DC5CD8E0>
Method 2:
def fib(): prev, curr = 0, 1 while True: yield curr prev, curr = curr, curr + prevf = fib()print(f) //Out:<generator object fib at 0x00000258DC5CD150>
After the definition is successful, we can use next () to access the next element of the generator.
print(next(gen)) //0print(next(gen)) //1...print(next(gen)) //16print(next(gen)) //StopIteration
However, we usually use for loop traversal.
for n in gen: print(n) //0 1 4 9 16
2. iterator
Any object that implements the _ iter _ and _ next _ () methods is an iterator. _ Iter _ returns the iterator itself, __next _ returns the next value in the container. So the generator is a special iterator, which has both internal methods.
A custom iterator is as follows:
class Fib: def __init__(self): self.prev = 0 self.curr = 1 def __iter__(self): return self def __next__(self): value = self.curr self.curr += self.prev self.prev = value return valuef = Fib() count = 1 for n in f: print(n) count = count+1 if count>=10: break//Out:1 1 2 3 5 8 13 21 34
3. iteratable objects
Objects such as list, tuple, set, dict, and str that can directly act on the for loop are called iteratable objects. The iteratable object implements the _ iter _ Method for returning the iterator.
demo = [1,2,3,4]print(isinstance(demo, Iterable)) //Trueiter_object = iter(demo)print(iter_object) //<list_iterator object at 0x00000258DC5EF748>