Explain in detail the differences between Iterator and Iterable in Python
- 2020-12-19 21:07:21
- OfStack
In Python, list, truple, str, dict can all be iterated, but they are not iterators. Why is that?
Because and iterators that have a quite different, list/truple/map/dict the size of the data is certain, that is to say how many things unknown. But the iterator is not. The iterator does not know how many times it will be executed, so it can be interpreted as not knowing how many elements there are. Every time next() is called once, it will go down 1 step, which is lazy.
To determine if you can iterate, use Iterable
from collections import Iterable
isinstance({}, Iterable) --> True
isinstance((), Iterable) --> True
isinstance(100, Iterable) --> False
To determine if it is an iterator, use Iterator
from collections import Iterator
isinstance({}, Iterator) --> False
isinstance((), Iterator) --> False
isinstance( (x for x in range(10)), Iterator) --> True
So,
Anything that can be for is Iterable
Anything that can next() is Iterator
Collection data types such as list, truple, dict, str are all Itrable not Iterator, but one Iterator object can be obtained through the iter() function
The for loop in Python is implemented through next
for x in [1,2,3,4,5]:
pass
Is equivalent to
# First get iterator object
it = iter([1,2,3,4,5])
while True:
try:
# To obtain the 1 A value
x = next(it);
except StopIteration:
# encounter StopIteration Just exit the loop
break