#PythonDay34

Опубликовано: 30 Май 2026
на канале: Geeks With Geeks
10
1

Python generators are special functions that allow you to iterate over a potentially infinite sequence of values without storing them all in memory simultaneously. They use the yield statement to produce a series of values lazily, one at a time, as they are requested.

Here's an example of a simple generator function that yields a sequence of square numbers:

```python
def square_numbers(n):
for i in range(n):
yield i ** 2

Using the generator to iterate over the square numbers
for num in square_numbers(5):
print(num)
```

In this example, the `square_numbers` function generates square numbers from 0 to `n-1` using the `yield` statement. When the generator function is called, it returns an iterator object. The `for` loop then iterates over this iterator, calling the generator function each time a new value is needed.

Generators are particularly useful when dealing with large datasets or infinite sequences because they conserve memory by producing values on-the-fly, rather than storing them all in memory at once. Additionally, generators can be composed and chained together using generator expressions and other generator functions to create complex data processing pipelines.


#Python #Generators #Iterator #LazyEvaluation #DataProcessing