Python yield keyword

1. What is yield in Python?

yield is a keyword used inside a function.

In simple words:
👉 yield sends one value at a time
👉 It pauses the function
👉 Next time, it continues from where it stopped

A function that uses yield is called a generator.

2. return vs yield (Very Important)

Using return


 

Output:


 

👉 return stops the function forever.

Using yield


 

Output:


 

👉 yield gives multiple values, one by one.

3. Why Use yield?

We use yield because:
✔ It saves memory
✔ It works with big data
✔ It gives values step by step

4. Simple yield Example

Example


 

5. How yield Works (Easy Explanation)

  1. Function starts

  2. yield gives a value

  3. Function pauses

  4. Next call → continues from same place

6. yield with Loop

Example


 

7. Getting Values Using next()

Example


 

8. yield vs List (Memory Example)

List (Uses More Memory)


 

Generator with yield (Uses Less Memory)


 

9. Multiple yield in One Function

Example


 

10. yield Stops Automatically

When function finishes, generator stops.

Example


 

👉 No error, it ends quietly.

11. Common Beginner Mistakes

❌ Using return Instead of yield


 

❌ Not a generator.

❌ Reusing Generator


 

👉 Generator works only once.

12. Real-Life Example (Read Data Slowly)

Example


 

13. Simple Practice Examples

Example 1: Even Numbers


 

Example 2: Countdown


 

Example 3: Squares


 

14. When Should You Use yield?

✔ When data is large
✔ When you want one value at a time
✔ When memory is important

15. Summary (Python yield)

yield creates a generator
✔ Returns values one by one
✔ Pauses and resumes function
✔ Saves memory
✔ Very powerful Python feature

📘 Perfect for Beginner & Intermediate eBook

This chapter is ideal for:

  • Python learners

  • Interview preparation

  • Writing efficient code

  • Real-world projects

If you want next, I can write:

  • Advanced Generators

  • yield vs return (Deep)

  • Iterator vs Generator

  • Python Performance Tips

Just tell me 😊

You may also like...