Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

The iterator

 

Iteration is a way of accessing elements of a collection. An iterator is an object that can remember the position to be traversed. Iterator objects are accessed from the first element of the collection until all elements have been accessed. Iterators can only move forward, not backward.

1. Iterable

Some python data types can be iterated directly through the for loop to get the value of an element, such as:

Set data types: list, tuple, dict, set, STR, etc

Generators include generators and generator functions with yield

These objects that can be directly applied to the for loop are collectively called iterables: Iterable

2. Check whether it is iterable

You can use the isinstance() function to determine if an object is an Iterable

>>> from collections import可迭代>>> isinstance([],Iterable)
>>> True

>>> isinstance({},Iterable)
>>> True

>>> isinstance("abc",Iterable)
>>> True

>>> isinstance((x for x in range(10)),Iterable)
>>> True

>>> isinstance(100,Iterable)
>>> False
Copy the code

We know that the generator can not only iterate through the for loop to retrieve elements, but can also call the next() function repeatedly to return the next value until it finally throws a StopIteration error indicating that it cannot return the next value.

3. The iterator

Objects that can be called by the next() function and keep returning the next value are called iterators: iterators.

Use isinstance() to determine if an object is an iterator:

>>> from collections import Iterator

>>> isinstance([],Iterator)
>>> False

>>> isinstance({},Iterator)
>>> False

>>> isinstance('abc',Iterator)
>>> False

>>> isinstance((x for x in range(10)),Iterator)
>>> True

>>> isinstance(100,Iterator)
>>> False
Copy the code

From the code above we can see that lists, collections, dictionaries, strings, etc. are iterables but not iterators. Generators are both iterables and iterators.

4. The iter () function

It says that all generators are iterators. Iterables like list, dict, and STR are not iterators, but they can be turned into iterators using iter(). As follows:

>>> isinstance(iter([]),Iterator)
>>> True

>>> isinstance(iter({}),Iterator)
>>> True

>>> isinstance(iter('abc'),Iterator)
>>> True
Copy the code

conclusion

  • All objects that operate on the for loop are of type Iterable
  • Any object that can be used as a next() function is of type Iterator
  • Set data types such as list, dict, and STR are Iterable but not iterators, but can be converted to iterators by the iter() function