Iterators and Generators
Iterators and generators are important memory-saving tools in Python. They allow you to work with sequences of data (of any size) without loading everything into memory at once. Instead, each member of the iterable is processed individually. This is especially useful when dealing with large datasets or streams of data.
What is an Iterable?
An iterable is any Python object that can return its members one at a time, allowing it to be iterated over using a loop (see For Loops and While Loops). The order in which iterables are iterated over depends on their type. For example:
- Sequentially: Lists, Tuples, and Strings.
- Insertion Order: Dictionaries.
- Unordered: Sets.
Tip
Not everything in Python is iterable. For example,
integers and
floats are not iterable. If you try to
iterate over them, you'll get a TypeError exception.
You can check if an object is iterable by using the isinstance() function
with the collections.abc.Iterable class.
| Checking if Iterable | |
|---|---|
- Integers are not iterable, so this will return
False.
Would return:
What is an Iterator?
An iterator is any object that implements the iterator protocol, which consists of two methods:
__iter__(): Returns the iterator object itself.__next__(): Returns the next value from the iterator. If there are no more items, it raises aStopIterationexception.