> For the complete documentation index, see [llms.txt](https://appsecurity.gitbook.io/devops/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://appsecurity.gitbook.io/devops/ppc/ppc-langs/backend/python/advanced/generators.md).

# Работа с генераторами

Генераторы — функции с ключевым словом `yield`. `yield` — ключевое слово в Python, которое используется для возврата из функции с сохранением состояния ее локальных переменных, и при повторном вызове такой функции выполнение продолжается с оператора yield, на котором ее работа была прервана.

Генератор — итератор, который можно итерировать только один раз.

Генератор, в отличие от итератора, не хранит последовательность в памяти.

## Еще сложные понятия около генераторов

### Collection comprehensions

Это генераторы коллекций — синтаксический сахар, позволяющий на лету генерить коллекции

### Generator object

Или generator iterator — это функция-генератор, которая один раз отдаст свои объекты (объекты итератора) и все

## Создание генератора

### Через функцию

```python
def get_numbers(start: int = 0, end: int = 1000):
   while start < end:
      yield start
      start += 1      
```

### Через генератор-выражение

```python
iterator = (num for num in range(1000))
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://appsecurity.gitbook.io/devops/ppc/ppc-langs/backend/python/advanced/generators.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
