w1coding.comAll tutorials

Python Generators

Python lessons
  1. Environment Setup
  2. Introduction
  3. Control
  4. Control
  5. Loops
  6. Functions
  7. Lists
  8. Dictionary
  9. Classes
  10. Exception
  11. File
  12. Libray
  13. Date
  14. Regula
  15. JSON
  16. Web
  17. Zweb
  18. Apis
  19. Unity
  20. Llampda
  21. Iterators
  22. Generators
  23. Files
  24. Context
  25. Ilogging
  26. Multithreading
  27. Networking
  28. SQLite

Python Generators

Generators are a simple way of creating iterators. They are written using the yield keyword instead of return.

Using Generators

Here is an example of a generator that yields the first n squares:

      
        def squares(n):
            for i in range(n):
                yield i * i

        for square in squares(5):
            print(square)
      
    

In this example, the squares function generates squares from 0 to n-1 using the yield keyword.

Activity

Try It Yourself!

Write a generator that yields Fibonacci numbers up to a given limit.

Quick Quiz

Quick Quiz

  1. What is the main difference between a generator and an iterator?
  2. What keyword is used to create a generator?

Answers: Generators use the yield keyword and are more memory-efficient than iterators. They produce values one at a time and don't store them in memory.