Generators in Python

IteradoresDecoradores

Generators are a special type of iterator that allow you to generate values on the fly, one at a time, instead of storing them all in memory at once.

They are perfect for working with large datasets, infinite sequences, or when you want to save memory. Generators use the yield keyword and are created with generator functions or generator expressions.

Generators are lazy – they produce values only when requested, making them efficient and powerful.

Generator Functions with yield

A generator function looks like a normal function but uses yield instead of return. Each yield produces a value and pauses the function.

Why Generators Save Memory

A normal list stores all values in memory. A generator produces values one by one.

Generator Expressions

A shorter syntax similar to list comprehensions, but with parentheses.

Sending Values to Generators

Use .send() to pass values back into a generator.

Real-World Use Cases

  • Reading large files line by line
  • Generating infinite sequences (e.g., Fibonacci)
  • Processing streams of data
  • Memory-efficient pipelines

Quick Quiz

Hemos revisado y comprobado los materiales, pero aún pueden existir errores. El contenido se ofrece únicamente con fines educativos, así que úsalo bajo tu propia responsabilidad y verifica con otras fuentes si es necesario.

✨ Pregunta a Lara — tu compañera de estudio con IA

Desbloquea soporte de aprendizaje personalizado. Lara puede explicar lecciones, resumir temas y responder tus preguntas — disponible desde el plan Go y superiores.


Lara te ayuda a aprender más rápido — exclusivo para los miembros ReadyTools Go, Plus y Max.

Sigue Tu Progreso 🚀

Aprende más fácilmente siguiendo tu progreso completamente gratis.