Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

11
  • 766
    yield is not as magical this answer suggests. When you call a function that contains a yield statement anywhere, you get a generator object, but no code runs. Then each time you extract an object from the generator, Python executes code in the function until it comes to a yield statement, then pauses and delivers the object. When you extract another object, Python resumes just after the yield and continues until it reaches another yield (often the same one, but one iteration later). This continues until the function runs off the end, at which point the generator is deemed exhausted. Commented May 23, 2017 at 21:41
  • 91
    "These iterables are handy... but you store all the values in memory and this is not always what you want", is either wrong or confusing. An iterable returns an iterator upon calling the iter() on the iterable, and an iterator doesn't always have to store its values in memory, depending on the implementation of the iter method, it can also generate values in the sequence on demand. Commented Feb 15, 2018 at 19:21
  • 38
    It would be nice to add to this great answer why It is just the same except you used () instead of [], specifically what () is (there may be confusion with a tuple).
    – WoJ
    Commented May 7, 2020 at 10:12
  • 49
    @MatthiasFripp "This continues until the function runs off the end" -- or it encounters a return statement. (return is permitted in a function containing yield, provided that it does not specify a return value.)
    – alani
    Commented Jun 6, 2020 at 6:03
  • 27
    The yield statement suspends function’s execution and sends a value back to the caller, but retains enough state to enable function to resume where it is left off. When resumed, the function continues execution immediately after the last yield run. This allows its code to produce a series of values over time, rather than computing them at once and sending them back like a list.
    – Jacob Ward
    Commented Dec 3, 2020 at 1:23