Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Yield Keyword
#1
Below is the code I have done following a tutorial, it involves creating a generator that makes the Fibonacci sequence, and then prints it out for values under 100. My problem that I have is I don't understand why I am using 'yield a' and what this does. Code is below:

def fib():
    a = 0
    b = 1
    while True:
        yield a
        a = b
        b = a + b
for f in fib():
    if f > 100:
        break
    print(f)
Reply
#2
You capture the value (a from fib in your loop) returned by fib, but don't do anything with it except for the last iteration.
you should save it to a list, or print out results immediately:

to list:
def fib():
    a = 0
    b = 1
    while True:
        yield a
        a = b
        b = a + b
fibs = []
for f in fib():
    fibs.append(f)
    if f > 100:
        break
print(fibs)
immediate:
def fib():
    a = 0
    b = 1
    while True:
        yield a
        a = b
        b = a + b
for f in fib():
    print('{}, '.format(f), end = '')
    if f > 100:
        break
print()
Reply
#3
(Aug-23-2018, 05:43 PM)6pathsMadara Wrote: Below is the code I have done following a tutorial, it involves creating a generator that makes the Fibonacci sequence, and then prints it out for values under 100. My problem that I have is I don't understand why I am using 'yield a' and what this does. Code is below:
def fib(): a = 0 b = 1 while True: yield a a = b b = a + b for f in fib(): if f > 100: break print(f)
(Aug-23-2018, 05:59 PM)Larz60+ Wrote: You capture the value (a from fib in your loop) returned by fib, but don't do anything with it except for the last iteration. you should save it to a list, or print out results immediately: to list:
 def fib(): a = 0 b = 1 while True: yield a a = b b = a + b fibs = [] for f in fib(): fibs.append(f) if f > 100: break print(fibs) 
immediate:
 def fib(): a = 0 b = 1 while True: yield a a = b b = a + b for f in fib(): print('{}, '.format(f), end = '') if f > 100: break print() 
But I still don't understand what yield does, when i remove it, the code doesn't do anything, there's no errors but it doesn't do anything, but I still don't understand it's functionality.
Reply
#4
yield returns one value for each iteration.
so every time fib() is called, it yields 1 more value.
It't like it has a jar of cookies, and it only gives you one, just one (each time you ask), but only when you ask for it
Reply
#5
return instead of yield would exit the function and forget about a and b (try it!). yield will return a value while retaining the state of the function in memory until the next time fib() is called. It will therefore remember what a and b were since the last time the function ran.
Reply
#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
#7
(Aug-24-2018, 08:30 AM)DeaD_EyE Wrote: 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.

Thank you, you have been great help and i now understand it.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  yield from akbarza 3 89 2 hours ago
Last Post: snippsat
  yield usage as statement or expression akbarza 5 796 Oct-23-2023, 11:43 AM
Last Post: Gribouillis
  Find a specific keyword after another keyword and change the output sgtmcc 5 808 Oct-05-2023, 07:41 PM
Last Post: deanhystad
  Using list comprehension with 'yield' in function tester_V 5 1,246 Apr-02-2023, 06:31 PM
Last Post: tester_V
  Yield generator weird output Vidar567 8 3,272 Nov-23-2020, 10:59 PM
Last Post: deanhystad
  Trying to access next element using Generator(yield) in a Class omm 2 1,967 Oct-19-2020, 03:36 PM
Last Post: omm
  Yield statement question DPaul 6 2,509 Sep-26-2020, 05:18 PM
Last Post: DPaul
  Problem about yield, please help!! cls0724 5 2,856 Apr-08-2020, 05:37 PM
Last Post: deanhystad
  does yield support variable args? Skaperen 0 1,670 Mar-03-2020, 02:44 AM
Last Post: Skaperen
  generator function that yield from a list buran 9 4,168 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