Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Yield Keyword
#6
A function where the yield keyword is used, is a generator.
Calling the function returns a generator object. This objects saves it's internal state.
The generator object is also an iterator.
This is where 'magic' comes in-place. Calling next() on a generator
object, executes the code until the first yield has been reached.

def gen1():
    yield 1337

g = gen1() # no code execution
next(g) # gives you 1337
next(g) # Raises StopIteration
Since Python 3.4 you can and should use the return statement inside a generator to stop the iteration. It's better then raise StopIteration, which makes trouble with newer version of Python.

The Fibonacci example has a loop, where the yield keyword is hit more than one time. This is the cause, why it behaves like a loop.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
Yield Keyword - by 6pathsMadara - Aug-23-2018, 05:43 PM
RE: Yield Keyword - by Larz60+ - Aug-23-2018, 05:59 PM
RE: Yield Keyword - by 6pathsMadara - Aug-23-2018, 06:26 PM
RE: Yield Keyword - by Larz60+ - Aug-23-2018, 08:39 PM
RE: Yield Keyword - by heras - Aug-23-2018, 08:39 PM
RE: Yield Keyword - by DeaD_EyE - Aug-24-2018, 08:30 AM
RE: Yield Keyword - by 6pathsMadara - Aug-24-2018, 11:43 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  yield from akbarza 4 492 Apr-19-2024, 07:58 PM
Last Post: DeaD_EyE
  yield usage as statement or expression akbarza 5 990 Oct-23-2023, 11:43 AM
Last Post: Gribouillis
  Find a specific keyword after another keyword and change the output sgtmcc 5 966 Oct-05-2023, 07:41 PM
Last Post: deanhystad
  Using list comprehension with 'yield' in function tester_V 5 1,399 Apr-02-2023, 06:31 PM
Last Post: tester_V
  Yield generator weird output Vidar567 8 3,408 Nov-23-2020, 10:59 PM
Last Post: deanhystad
  Trying to access next element using Generator(yield) in a Class omm 2 2,080 Oct-19-2020, 03:36 PM
Last Post: omm
  Yield statement question DPaul 6 2,603 Sep-26-2020, 05:18 PM
Last Post: DPaul
  Problem about yield, please help!! cls0724 5 3,010 Apr-08-2020, 05:37 PM
Last Post: deanhystad
  does yield support variable args? Skaperen 0 1,728 Mar-03-2020, 02:44 AM
Last Post: Skaperen
  generator function that yield from a list buran 9 4,391 Jun-04-2019, 10:26 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020