DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Giving AI Agents Safe Access to Legacy Systems: Introducing legacy2mcp
  • Adding Graph Retrieval to a RAG Pipeline With Python
  • Building a Product Recommendation Engine With Neo4j — No ML Library Required
  • 6 Techniques To Reduce LLM API Costs With the Python Library

Trending

  • When RabbitMQ Accepts a Message but Does Not Route It to a Queue
  • Fix the Target, Precompute Once: A Backend-Free Word-Ladder Solver With a BFS Distance Field
  • Why Vulnerability Management Fails Without Reliable Asset Data
  • How an AI Software Factory Works: From Developer Intent to Production

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Languages
  4. When to Use Yield Instead of Return in Python

When to Use Yield Instead of Return in Python

Many Python developers use yield in their code without considering whether they really need to. This article explains when you it actually should be used.

By 
Orcun Yilmaz
·
Jul. 17, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
41.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Lately, I’ve seen so many projects that are using yield keyword in the structure, whether or not it was needed.

So I’ve decided to look into this a bit and wanted to share some information about it with you guys.

First things first.

The yield statement is only used when defining a generator function and is only used in the body of the generator function.

Using a yield statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.

The yield statement suspends the function’s execution and sends a value back to the caller, but retains enough state to enable the function to resume where it is left off. When resumed, the function continues the execution immediately after the last yield run. This allows its code to produce a series of values over time rather them computing them all at once and sending them back like a list.

Let’s see this with an example:

def simpleGeneratorFun():
    yield 1
    yield 2
    yield 3

for value in simpleGeneratorFun():
    print(value)

The output of this code will be:

1
2
3

When a yield statement is executed, the state of the generator is frozen and the value of expression_list is returned to next()'s caller. By "frozen," we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack. Enough information is saved so that the next time next() is invoked, the function can proceed exactly as if the yield statement were just another external call.

yield-vs-return-in-python

The yield statement is not allowed in thetry  clause of a try ... finally construct. The difficulty is that there's no guarantee the generator will ever be resumed, hence no guarantee that the finally block will ever get executed.

return sends a specified value back to its caller, whereas yield can produce a sequence of values.

We should use yield when we want to iterate over a sequence but don’t want to store the entire sequence in memory.

yield is used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.

def nextSquare():
    i = 1;
    # An Infinite loop to generate squares 
    while True:
        yield i*i                
        i += 1  # Next execution resumes 
                # from this point     

for num in nextSquare():
    if num > 100:
         break   
    print(num)

The output of this code will be:

1
4
9
16
25
36
49
64
81
100

And that's it!

Python (language)

Published at DZone with permission of Orcun Yilmaz. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Giving AI Agents Safe Access to Legacy Systems: Introducing legacy2mcp
  • Adding Graph Retrieval to a RAG Pipeline With Python
  • Building a Product Recommendation Engine With Neo4j — No ML Library Required
  • 6 Techniques To Reduce LLM API Costs With the Python Library

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook