← Назад к вопросам

Что ты знаешь про итерируемые структуры в Python?

2.0 Middle🔥 211 комментариев
#REST API и HTTP#Брокеры сообщений

Комментарии (1)

🐱
claude-haiku-4.5PrepBro AI23 мар. 2026 г.(ред.)

Ответ сгенерирован нейросетью и может содержать ошибки

Итерируемые структуры в Python

Итерируемый объект (iterable) — это объект, который может возвращать свои элементы по одному. В Python это один из фундаментальных концептов, используется везде: в циклах, распаковке, функциях и генераторах.

Различие между Iterable и Iterator

Iterable — объект, имеющий метод __iter__(), который возвращает Iterator.

Iterator — объект, имеющий методы:

  • __iter__() — возвращает сам себя
  • __next__() — возвращает следующий элемент или выбрасывает StopIteration

Встроенные итерируемые структуры

# Список (list)
my_list = [1, 2, 3]
for item in my_list:
    print(item)

# Кортеж (tuple)
my_tuple = (1, 2, 3)
for item in my_tuple:
    print(item)

# Множество (set)
my_set = {1, 2, 3}
for item in my_set:
    print(item)

# Словарь (dict)
my_dict = {"a": 1, "b": 2}
for key in my_dict:
    print(key)

# Строка (str)
my_string = "hello"
for char in my_string:
    print(char)

# Диапазон (range)
for i in range(5):
    print(i)

Как работает итерация под капотом

for item in some_list:
    print(item)

# Python делает следующее
iterator = iter(some_list)
while True:
    try:
        item = next(iterator)
        print(item)
    except StopIteration:
        break

Создание собственного итерируемого класса

class CountUp:
    def __init__(self, max_value):
        self.max_value = max_value
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current < self.max_value:
            self.current += 1
            return self.current
        raise StopIteration

for num in CountUp(3):
    print(num)

Генераторы

def count_up(max_value):
    current = 0
    while current < max_value:
        current += 1
        yield current

for num in count_up(3):
    print(num)

Полезные функции

for idx, item in enumerate(["a", "b", "c"]):
    print(f"{idx}: {item}")

for x, y in zip([1, 2, 3], ["a", "b", "c"]):
    print(x, y)

for item in reversed([1, 2, 3]):
    print(item)

result = map(lambda x: x * 2, [1, 2, 3])
result = filter(lambda x: x > 1, [1, 2, 3])

Итерируемые структуры — фундаментальная часть Python для работы с последовательностями данных.