Python3 Iterator Generator
# Python3.x Python3 Iterators and Generators
* * *
## Iterators
Iteration is one of Python's most powerful features and is a way to access elements in a collection.
An iterator is an object that remembers the position during traversal.
An iterator object starts accessing elements from the first element of the collection and continues until all elements have been accessed. An iterator can only move forward, not backward.
An iterator has two basic methods: **iter()** and **next()**.
Strings, lists, or tuple objects can 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 as follows:
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 as follows:
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. This iterator object implements the `__next__()` method and signals the end of iteration with the `StopIteration` exception.
The `__next__()` method (which is `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 of the execution 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 trigger the `StopIteration` exception after a specified number of iterations to end the iteration.
Stop execution 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 of the execution is:
1234567891011121314151617181920
* * *
## Generators
In Python, a function that uses **yield** is called a generator.
**yield** is a keyword used to define generator functions. A generator function is a special type of function that can produce values incrementally during iteration, rather than returning all results at once.
Unlike a regular function, a generator is a function that returns an iterator and 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 of 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 incrementally 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