What is “yield” or “generator” in Python?

What is a “coroutine” in Python?

Harshal Parekh
The Startup

--

A lot of new python learners have a hard time wrapping their brain around PEP 380. I am usually asked:

  1. What does the “yield” keyword do?
  2. What are the situations where “yield from” is useful?
  3. What is the classic use case?
  4. Why is it compared to micro-threads?

To understand what yield does, you must understand what generators are. And before you can understand generators, you must understand iterables.

Iterables

An iterable is an object that has an __iter__ method which returns an iterator, or which defines a __getitem__ method that can take sequential indexes starting from zero (and raises an IndexError when the indexes are no longer valid). So an iterable is an object that you can get an iterator from.

  • anything that can be looped over (i.e. you can loop over a string or file) or
  • anything that can appear on the right-side of a for-loop: for x in iterable: ... or
  • anything you can call with iter() that will return an ITERATOR: iter(obj)
>>> mylist = [1, 2, 3]
>>> # mylist = [x*x for x in range(3)] # or a list comprehension
>>> for i in

--

--