Home >Backend Development >Python Tutorial >How Does Python's `yield` Keyword Create and Manage Generators?
Understanding the yield keyword in Python requires familiarity with iterables and generators.
Iterables are objects like lists and strings that can be iterated over one element at a time.
Generators are iterators that produce values one at a time without storing the entire sequence in memory.
The yield keyword functions like a return statement in a generator function. However, instead of ending the function, it pauses execution and returns a value. When the iterator resumes, execution continues from where it paused.
Generator:
def _get_child_candidates(self, distance, min_dist, max_dist): # Check if a left child exists and the distance is within range if self._leftchild and distance - max_dist < self._median: yield self._leftchild # Check if a right child exists and the distance is within range if self._rightchild and distance + max_dist >= self._median: yield self._rightchild
This generator function returns child nodes within the specified distance range.
Caller:
result, candidates = [], [self] # Initialize empty result and candidates list while candidates: # Iterate while candidates are available node = candidates.pop() distance = node._get_dist(obj) if distance <= max_dist and distance >= min_dist: # Check distance range result.extend(node._values) candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) # Add children to candidates list return result
The caller initializes and iterates through a list of candidate nodes, using the generator function to expand the candidates list while looping. It checks the distance range and adds child nodes if appropriate.
The yield keyword enables control over generator exhaustion. By setting a flag to stop iteration, you can pause and resume access to generator values.
The itertools module provides functions to manipulate iterables. For example, you can create permutations of a list easily.
The above is the detailed content of How Does Python's `yield` Keyword Create and Manage Generators?. For more information, please follow other related articles on the PHP Chinese website!