Python3 Iterators and Generators
iterator
Iteration is one of Python's most powerful features and a way to access the elements of a collection.
An iterator is an object that can remember the position of a traversal.
An iterator object starts accessing at the first element of a collection and ends when all elements have been visited. Iterators can only move forward, never backward.
An iterator has two basic methods:iter() and next()。
String, list and tuple objects can all be used to create iterators:
Example (Python 3.0+)
list
=
[
1
,
2
,
3
,
4
]
it
=
iter
(
list
)
Create an iterator object
(
next
(
it
)
)
Output the next element of the iterator
1
(
next
(
it
)
)
2
An iterator object can be traversed with a regular for statement:
Example (Python 3.0+)
#!/usr/bin/python3
list
=
[
1
,
2
,
3
,
4
]
it
=
iter
(
list
)
Create an iterator object
for
x
in
it
:
(
x
,
end
=
"
"
)
Running the above program produces the following output:
1 2 3 4
You can also use the next() function:
Example (Python 3.0+)
#!/usr/bin/python3
import
sys
Import the sys module
list
=
[
1
,
2
,
3
,
4
]
it
=
iter
(
list
)
Create an iterator object
while
True
:
try
:
(
next
(
it
)
)
except
StopIteration
:
sys
.
exit
(
)
Running the above program produces the following output:
1
2
3
4
Create an iterator
To use a class as an iterator, two methods must be implemented in the class iter() and next() 。
If you already understand object-oriented programming, you know that every class has a constructor; Python's constructor is init(), which is executed when the object is initialized.
For more details, see:Python3 Object-Oriented Programming
iter() method returns a special iterator object that implements the next() method and signals the completion of iteration with the StopIteration exception.
next() method (next() in Python 2) returns the next iterator object.
Create an iterator that returns numbers, starting at 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
)
(
next
(
myiter
)
)
(
next
(
myiter
)
)
(
next
(
myiter
)
)
(
next
(
myiter
)
)
(
next
(
myiter
)
)
The execution output is:
1
2
3
4
5
StopIteration
The StopIteration exception signals the completion of iteration and prevents infinite loops; in the next() method we can arrange to raise StopIteration after a specified number of loops 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
:
(
x
)
The execution output is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Generator
In Python, functions that use yield are called generators.
yield is a keyword used to define a generator function, a special kind of function that produces values step by step during iteration instead of returning all results at once.
Unlike ordinary functions, a generator is a function that returns an iterator and can only be used for iteration; more simply, a generator is an iterator.
When the yield statement is used in a generator function, execution of the function is suspended and the yield expression following it is returned as the value of the current iteration.
Then, each time the generator's next() method is called or the for loop is used to iterate, the function resumes from where it was suspended until it encounters the yield statement again. In this way, a generator function can produce values step by step instead of computing and returning all results at once.
Calling a generator function returns an iterator object.
The following is a simple example showing the use of a generator function:
Example
def
countdown
(
n
)
:
while
n
0
:
yield
n
n
-=
1
Create a generator object
generator
=
countdown
(
5
)
Get values by iterating over the generator
(
next
(
generator
)
)
Output: 5
(
next
(
generator
)
)
Output: 4
(
next
(
generator
)
)
Output: 3
Iterate over the generator with a for loop
for
value
in
generator
:
(
value
)
Output: 2 1
In the above example, thecountdown function is a generator function. It uses the yield statement to produce countdown numbers from n down to 1 step by step. Each time yield is called, the function returns the current countdown value and resumes from where it was suspended on the next call.
By creating a generator object and using the next() function or a for loop, we can obtain the values produced by the generator function step by step. In this example, we first use next() to get the first three countdown values, then use a for loop to get the remaining two.
The advantage of generator functions is that they produce values on demand, avoiding generating large amounts of data at once and using lots of memory. In addition, generators work seamlessly with other iteration tools such as for loops, providing a concise and efficient way to iterate.
Running the above program produces the following output:
5
4
3
2
1
The following example uses yield to implement the Fibonacci sequence:
Example (Python 3.0+)
#!/usr/bin/python3
import
sys
def
fibonacci
(
n
)
:
Generator function - Fibonacci
a
,
b
,
counter
=
0
,
1
,
0
while
True
:
if
(
counter
n
)
:
return
yield
a
a
,
b
=
b
,
a
b
counter
+=
1
f
=
fibonacci
(
10
)
f is an iterator produced by the generator
while
True
:
try
:
(
next
(
f
)
,
end
=
"
"
)
except
StopIteration
:
sys
.
exit
(
)
Running the above program produces the following output:
0 1 1 2 3 5 8 13 21 34 55