These objects that can act directly on for
loops are collectively called iterable objects: Iterable
.
You can use to isinstance()
determine whether an object is an Iterable
object:
>>> from collections import Iterable
>>> isinstance([], Iterable)
True >>> isinstance({}, Iterable) True >>> isinstance('abc', Iterable) True >>> isinstance((x for x in range(10)), Iterable) True >>> isinstance(100, Iterable) False
An object that can be called by next()
a function and keeps returning the next value is called an iterator: Iterator
.
You can use to isinstance()
determine whether an object is an Iterator
object:
>>> from collections import Iterator
>>> isinstance((x for x in range(10)), Iterator) True >>> isinstance([], Iterator) False >>> isinstance({}, Iterator) False >>> isinstance('abc', Iterator) False
Generators are Iterator
objects, but list
, dict
, str
although they are Iterable
, but they are not Iterator
.
Turn list
, dict
, str
etc Iterable
into Iterator
usable iter()
functions:
>>> isinstance(iter([]), Iterator)
True
>>> isinstance(iter('abc'), Iterator)
True
You might ask, why are list
, dict
, , str
etc. data types not Iterator
?
This is because Python Iterator
objects represent a stream of data, and the Iterator object can be called by next()
a function and keep returning the next data until StopIteration
an error is thrown when there is no data. This data stream can be regarded as an ordered sequence, but we cannot know the length of the sequence in advance, and can only continuously next()
calculate the next data on demand through the function, so Iterator
the calculation is lazy, only when the next data needs to be returned it will only be calculated.
Iterator
It can even represent an infinite data stream, such as all natural numbers. And using list is never possible to store all natural numbers.