python generator - What does the “yield” keyword do?
python generator to list / python / iterator / generator / yield / coroutine
What is the use of the
yield keyword in Python, and what does it do?
For example, I'm trying to understand this code1:
def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist < self._median: yield self._leftchild if self._rightchild and distance + max_dist >= self._median: yield self._rightchild
And this is the caller:
result, candidates = , [self] while candidates: node = candidates.pop() distance = node._get_dist(obj) if distance <= max_dist and distance >= min_dist: result.extend(node._values) candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) return result
Instead of this:
def square_list(n): the_list =  # Replace for x in range(n): y = x * x the_list.append(y) return the_list
def square_yield(n): for x in range(n): y = x * x yield y # with this one.
Whenever you find yourself building a list from scratch,
yield each piece instead.
yield is a sugary way to say
for square in square_list(4): print(square) 0 1 4 9 for square in square_yield(4): print(square) 0 1 4 9
Yield is versatile. Data doesn't have to be stored all together, it can be made available one at a time. It can be infinite.
def squares_all_of_them(): x = 0 while True: yield x * x x += 1 squares = squares_all_of_them() for _ in range(4): print(next(squares)) 0 1 4 9
>>> list(square_yield(4)) [0, 1, 4, 9]