Python Generators: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 11: Line 11:


=Overview=
=Overview=
A generator is a way to construct a new [[Python_Iterators#Overview|iterable]] object. Whereas normal functions execute and return a single result at a time, generators can return a sequence of multiple values by pausing and resuming execution each time the generator is used. To create a generator, use the <code>yield</code> keyword instead of <code>return</code> in a function.
A generator is a way to construct a new [[Python_Iterators#Overview|iterable]] object. Whereas normal functions execute and return a single result at a time, generators can return a sequence of multiple values by pausing and resuming execution each time the generator is used. To create a generator, use the <code>[[Python_Language#yield|yield]]</code> keyword instead of <code>return</code> in a function.


=Use Cases=
=Use Cases=


Create a [[Python_Language_List#Pass_a_Generator_Expression|list with a generator]].
Create a [[Python_Language_List#Pass_a_Generator_Expression|list with a generator]].

Revision as of 19:01, 17 May 2024

Internal

TODO

  • PROCESS IPy Generators Page 101.
  • PROCESS PyOOP "Generator expressions"
  • PROCESS PyOOP "Generators" + "Yield items from another iterable"

Overview

A generator is a way to construct a new iterable object. Whereas normal functions execute and return a single result at a time, generators can return a sequence of multiple values by pausing and resuming execution each time the generator is used. To create a generator, use the yield keyword instead of return in a function.

Use Cases

Create a list with a generator.