Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Iterator
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Generator== {{Main|Generator (computer science)}} One way of implementing an iterator is via a restricted form of [[coroutine]], known as a [[Generator (computer science)|generator]]. By contrast with a [[subroutine]], a generator coroutine can ''yield'' values to its caller multiple times, instead of returning just once. Most iterators are naturally expressible as generators, but because generators preserve their local state between invocations, they're particularly well-suited for complicated, stateful iterators, such as [[tree traversal|tree traversers]]. There are subtle differences and distinctions in the use of the terms "generator" and "iterator", which vary between authors and languages.<ref>{{cite web |url = http://www.csd.uwo.ca/ |title = A Technique for Generic Iteration and Its Optimization |last1 = Watt |first1 = Stephen M. |format = PDF |publisher = The University of Western Ontario, Department of Computer Science |archive-url = https://web.archive.org/web/20120806072711/http://www.csd.uwo.ca/ |archive-date = 2012-08-06 |quote = Some authors use the term iterator, and others the term generator. Some make subtle distinctions between the two. |access-date = 2012-08-08 |url-status = bot: unknown }}</ref> In [[Python (programming language)|Python]], a generator is an iterator [[Constructor (object-oriented programming)|constructor]]: a function that returns an iterator. An example of a Python generator returning an iterator for the [[Fibonacci number]]s using Python's <code>yield</code> statement follows: <syntaxhighlight lang="python"> def fibonacci(limit): a, b = 0, 1 for _ in range(limit): yield a a, b = b, a + b for number in fibonacci(100): # The generator constructs an iterator print(number) </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)