Iterator
1. The concept of iteration
Iteration is a way to access collection elements. An iterator in Python is an object that can remember traversal locations. The iterator object starts to access the first element of the collection until all elements are accessed. The iterator can only move forward and not backward.
2. Basic methods of iterators
There are two basic methods for iterators:
-
iter()
: Create an iterator object. -
next()
: Returns the next element of the iterator.
3. Create and use iterators
Example 1: Create an iterator using built-in objects
list = [1, 2, 3, 4] it = iter(list) # Create an iterator objectprint(next(it)) # Output the next element of the iteratorprint(next(it))
-
list = [1, 2, 3, 4]
: Define a list. -
it = iter(list)
:useiter()
The function creates an iterator object. -
print(next(it))
:usenext()
Function gets the next element of the iterator.
Example 2: Use for loop to traverse the iterator
list = [1, 2, 3, 4] it = iter(list) # Create an iterator objectfor x in it: print(x, end=" ")
-
for x in it:
: Use for loop to traverse the iterator object. -
print(x, end=" ")
: Print each element,end=" "
Used to output on the same line.
Example 3: Use while loop and try-except to handle iterators
import sys # Introduce the sys module list = [1, 2, 3, 4] it = iter(list) # Create an iterator object while True: try: print(next(it)) except StopIteration: ()
-
while True:
: Infinite loop. -
try:
: Try to executenext(it)
Get the next element. -
except StopIteration:
:CaptureStopIteration
Exception indicates the end of iteration. -
()
: Exit the program.
4. Create a custom iterator
To use a class as an iterator, two methods need to be implemented in the class:__iter__()
and__next__()
。
Example 1: Create a simple custom iterator
class MyNumbers: def __iter__(self): = 1 return self def __next__(self): x = += 1 return x myclass = MyNumbers() myiter = iter(myclass) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter)) print(next(myiter))
-
class MyNumbers:
: Define a class. -
def __iter__(self):
:accomplish__iter__()
Method, return an iterator object. -
def __next__(self):
:accomplish__next__()
Method, return the next element. -
myclass = MyNumbers()
: Create an instance of the class. -
myiter = iter(myclass)
: Create an iterator object. -
print(next(myiter))
:usenext()
Function gets the next element of the iterator.
Example 2: Create a limited custom iterator
class MyNumbers: def __iter__(self): = 1 return self def __next__(self): if <= 20: x = += 1 return x else: raise StopIteration myclass = MyNumbers() myiter = iter(myclass) for x in myiter: print(x)
-
if <= 20:
: Determine whether the iteration limit is reached. -
raise StopIteration
: ThrowStopIteration
Exception indicates the end of iteration. -
for x in myiter:
: Use for loop to traverse the iterator object.
Generator
1. The concept of generator
The generator is a special iterator that usesyield
Keyword definition. The generator function produces values step by step during iteration, rather than returning all results at once.
2. Basic usage of generator
The generator function returns an iterator object that can gradually generate values during the iteration process.
Example 1: Use the generator to implement countdown
def countdown(n): while n > 0: yield n n -= 1 # Create a generator objectgenerator = countdown(5) # Get the value through the iterative generatorprint(next(generator)) # Output: 5print(next(generator)) # Output: 4print(next(generator)) # Output: 3 # Use the for loop iterating generatorfor value in generator: print(value) # Output: 2 1
-
def countdown(n):
: Define a generator function. -
yield n
: Generate the current reciprocal value. -
n -= 1
: Decreasing count. -
generator = countdown(5)
: Create a generator object. -
print(next(generator))
:usenext()
Function gets the next value of the generator. -
for value in generator:
: Use for loop to traverse the generator object.
3. Advantages of generators
The main advantage of generators is that they can generate values on demand, avoiding generating large amounts of data at once and consuming a lot of memory. In addition, the generator can be used seamlessly with other iterative tools such as for loops, providing a simple and efficient way of iterating.
Example 2: Implementing Fibonacci sequences using generators
def fibonacci(n): 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, generated by the generator while True: try: print(next(f), end=" ") except StopIteration: ()
-
def fibonacci(n):
: Define a generator function. -
a, b, counter = 0, 1, 0
: Initialize the variable. -
if counter > n:
: Determine whether the generation limit is reached. -
yield a
: Generate the current Fibonacci number. -
a, b = b, a + b
: Updated Fibonacci numbers. -
counter += 1
: Increment count. -
f = fibonacci(10)
: Create a generator object. -
while True:
: Infinite loop. -
try:
: Try to executenext(f)
Get the next value. -
except StopIteration:
:CaptureStopIteration
Exception indicates the end of iteration. -
()
: Exit the program.
Summarize
This article details how to use iterators and generators in Python, and demonstrates how they work and application scenarios through specific code examples. By using the iter() and next() methods, we can create and use iterator objects. By using the yield keyword, we can define generator functions and generate values step by step. The advantage of generators is that they can generate values on demand, avoiding generating large amounts of data at once and consuming a lot of memory.
The above is a detailed explanation of the use of iterators and generators in Python. For more information about Python iterators and generators, please pay attention to my other related articles!