What does the "yield" word do in Python

1 min readFundamentalsBuilt-inAdvancedGenerators
7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

In Python, the "yield" keyword is used in the body of a function definition. When a function is called with a "yield" statement, it returns a generator object, but does not start execution immediately.

The function can be "resumed" from where it left off, each time the generator's next() method is called. This allows the function to produce a series of values over time, rather than computing them all at once and returning them in a list, for example.

For example, the following function uses "yield" to generate the sequence of Fibonacci numbers:

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

And this can be used in the following way:

>>> fib = fibonacci()
>>> fib.next()
0
>>> fib.next()
1
>>> fib.next()
1
>>> fib.next()
2

It's also important to mention that when a function defined with yield is called, it returns a generator object, but does not start execution immediately. Execution only begins when the generator's next() method is called for the first time.

7-Day Challenge

Land Your First Data Science Job

A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

Master Data Science in Days, Not Months 🚀

Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.