Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda The Iterator Protocol | Understanding Iterators
Efficient Data Handling in Python

bookThe Iterator Protocol

Deslize para mostrar o menu

Understanding how Python handles iteration is essential for working with sequences, loops, and many built-in features. At the core of this functionality is the iterator protocol. The iterator protocol is a set of methods that allows objects to be iterated over, meaning you can use them in a for loop or with functions like list() and sum(). In Python, an object is considered iterable if it implements the __iter__ method, which should return an iterator. An iterator is an object that implements both the __iter__ and __next__ methods. The __next__ method returns the next item in the sequence, and raises a StopIteration exception when there are no more items.

123456789101112131415161718
class CountUpTo: def __init__(self, max): self.max = max self.current = 1 def __iter__(self): return self def __next__(self): if self.current > self.max: raise StopIteration value = self.current self.current += 1 return value counter = CountUpTo(3) for number in counter: print(number)
copy

In this example, the CountUpTo class is a custom iterator. It keeps track of the current number and stops iteration when it reaches the maximum value. By defining both __iter__ and __next__, this class can be used in a for loop, which will automatically call __iter__ to get the iterator and then repeatedly call __next__ to retrieve each value.

1. Which of the following best describes the purpose of the __iter__ method in the iterator protocol?

2. Which of the following objects in Python are considered iterable?

question mark

Which of the following best describes the purpose of the __iter__ method in the iterator protocol?

Selecione a resposta correta

question mark

Which of the following objects in Python are considered iterable?

Selecione todas as respostas corretas

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 1

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 1. Capítulo 1
some-alt