Python3 Iterator Generator
# Python3.x Python3 Iterators and Generators
* * *
## Iterators
Iteration is one of Python's most powerful features, and a way to access elements in a collection.
An iterator is an object that can remember the position during traversal.
Iterator objects start accessing from the first element of the collection until all elements have been accessed. Iterators can only move forward, not backward.
Iterators have two basic methods: **iter()** and **next()**.
Strings, lists, or tuple objects can all be used to create iterators:
## Example (Python 3.0+)
>>>list=[1,2,3,4]
>>> it =iter(list)# Create iterator object
>>>print(next(it))# Output the next element of the iterator
1
>>>print(next(it))
2
>>>
Iterator objects can be traversed using a regular for loop:
## Example (Python 3.0+)
#!/usr/bin/python3 list=[1,2,3,4]it = iter(list)# Create iterator object for x in it: print(x, end="")
Executing the above program, the output result is:
1 2 3 4
You can also use the next() function:
## Example (Python 3.0+)
#!/usr/bin/python3 import sys# Import sys module list=[1,2,3,4]it = iter(list)# Create iterator object while True: try: print(next(it))except StopIteration: sys.exit()
Executing the above program, the output result is:
1234
### Creating an Iterator
To use a class as an iterator, you need to implement two methods in the class: __iter__() and __next__().
If you are already familiar with object-oriented programming, you know that classes have a constructor. Python's constructor is __init__(), which executes when the object is initialized.
For more information, see: (#)
The __iter__() method returns a special iterator object, which implements the __next__() method and signals the end of iteration via the StopIteration exception.
The __next__() method (next() in Python 2) returns the next iterator object.
Create an iterator that returns numbers, starting from 1 and incrementing by 1:
## Example (Python 3.0+)
class MyNumbers: def __iter__ (self): self.a = 1 return self def __next__ (self): x = self.a self.a += 1 return x myclass = MyNumbers()myiter = iter(myclass)print(next(myiter))print(next(myiter))print(next(myiter))print(next(myiter))print(next(myiter))
The output result is:
12345
### StopIteration
The StopIteration exception is used to signal the end of iteration, preventing infinite loops. In the __next__() method, we can set it to raise the StopIteration exception after a specified number of iterations to end the iteration.
Stop after 20 iterations:
## Example (Python 3.0+)
class MyNumbers: def __iter__ (self): self.a = 1 return self def __next__ (self): if self.a<= 20: x = self.a self.a += 1 return x else: raise StopIteration myclass = MyNumbers()myiter = iter(myclass)for x in myiter: print(x)
The output result is:
1234567891011121314151617181920
* * *
## Generators
In Python, a function that uses **yield** is called a generator (generator).
**yield** is a keyword used to define generator functions. Generator functions are special functions that can produce values step by step during iteration, rather than returning all results at once.
Unlike regular functions, a generator is a function that returns an iterator, which can only be used for iteration. To put it simply, a generator is an iterator.
When a **yield** statement is used in a generator function, the function's execution will pause, and the expression after **yield** will be returned as the value for the current iteration.
Then, each time the generator's **next()** method is called or a **for** loop is used for iteration, the function will resume execution from where it last paused until it encounters another **yield** statement. This way, the generator function can produce values step by step without needing to compute and return all results at once.
Calling a generator function returns an iterator object.
Here is a simple example demonstrating the use of a generator function:
YouTip