Generators in Python
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
Wir haben die Materialien überprüft, dennoch können Fehler vorkommen. Der Inhalt dient ausschließlich Bildungszwecken, daher verwende ihn auf eigene Verantwortung und überprüfe ihn bei Bedarf mit anderen Quellen.
✨ Frag Lara — deine KI-Lernpartnerin
Entsperre personalisierte Lernunterstützung. Lara kann Lektionen erklären, Themen zusammenfassen und deine Lernfragen beantworten — verfügbar ab dem Go-Tarif.
Lara hilft dir, schneller zu lernen — exklusiv für ReadyTools Go-, Plus- und Max-Mitglieder.

