Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Understanding Iterators in Python | Mastering Iterators and Generators in Python
Python Advanced Concepts

Deslize para mostrar o menu

book
Understanding Iterators in Python

What Are Iterators?

Technically, in Python, an iterator is an object that implements the iterator protocol, which consists of the following methods:

  • __iter__() : returns the iterator object itself, making it compatible with loops like for ;

  • __next__() : returns the next element in the sequence. When no elements remain, it raises a StopIteration exception to signal the end of traversal.

An iterator enables traversal of elements in an iterable (e.g., list or string) one at a time while keeping track of its position.

python

Note

An iterator is also an iterable because it implements the __iter__() method.

Not all iterables are iterators. For example, a list is iterable but not an iterator. When you pass it to the iter() function, you get an iterator that allows element-by-element traversal.

Building a Custom Iterator

This iterator generates a fixed number of random dice rolls and stops once all rolls are completed.

123456789101112131415161718192021222324252627
import random class FiniteDie: def __init__(self, num_rolls): """Initialize the iterator with a fixed number of rolls.""" self.num_rolls = num_rolls self.current_roll = 0 def __iter__(self): """Return the iterator object itself.""" return self def __next__(self): """Generate the next dice roll or stop iteration.""" if self.current_roll < self.num_rolls: self.current_roll += 1 return random.randint(1, 6) raise StopIteration # Using the FiniteDie iterator num_rolls = 5 die_iterator = FiniteDie(num_rolls) print(f"Rolling the die {num_rolls} times:") for roll in die_iterator: print(f"Rolled: {roll}")
copy

Iterator Exhaustion

Once an iterator is exhausted, it cannot be reused without recreating it. For example:

12345678910
numbers = [1, 2, 3, 4] iterator = iter(numbers) # First iteration for num in iterator: print(num) # Output: 1, 2, 3, 4 # Second iteration for num in iterator: print(num) # Output: Nothing, the iterator is exhausted.
copy

Iterators can only be traversed once. To iterate again, a new iterator needs to be created.

Tarefa

Swipe to start coding

Complete the missing parts of the code to implement a custom iterator class for simulating an infinite die roller. The iterator should lazily generate random rolls of a six-sided die and stop after 10 rolls.

  1. The __iter__() method allows an object to be used as an iterator.
  2. The __next__() method produces the next random die roll (a number between 1 and 6).
  3. Create an instance of the InfiniteDie class, which represents the die roller.
  4. Use a for loop with enumerate() to roll the die lazily. Stop after 10 rolls using an if condition and the break statement.

Solução

Switch to desktopMude para o desktop para praticar no mundo realContinue de onde você está usando uma das opções abaixo
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 6. Capítulo 2

Pergunte à IA

expand
ChatGPT

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

book
Understanding Iterators in Python

What Are Iterators?

Technically, in Python, an iterator is an object that implements the iterator protocol, which consists of the following methods:

  • __iter__() : returns the iterator object itself, making it compatible with loops like for ;

  • __next__() : returns the next element in the sequence. When no elements remain, it raises a StopIteration exception to signal the end of traversal.

An iterator enables traversal of elements in an iterable (e.g., list or string) one at a time while keeping track of its position.

python

Note

An iterator is also an iterable because it implements the __iter__() method.

Not all iterables are iterators. For example, a list is iterable but not an iterator. When you pass it to the iter() function, you get an iterator that allows element-by-element traversal.

Building a Custom Iterator

This iterator generates a fixed number of random dice rolls and stops once all rolls are completed.

123456789101112131415161718192021222324252627
import random class FiniteDie: def __init__(self, num_rolls): """Initialize the iterator with a fixed number of rolls.""" self.num_rolls = num_rolls self.current_roll = 0 def __iter__(self): """Return the iterator object itself.""" return self def __next__(self): """Generate the next dice roll or stop iteration.""" if self.current_roll < self.num_rolls: self.current_roll += 1 return random.randint(1, 6) raise StopIteration # Using the FiniteDie iterator num_rolls = 5 die_iterator = FiniteDie(num_rolls) print(f"Rolling the die {num_rolls} times:") for roll in die_iterator: print(f"Rolled: {roll}")
copy

Iterator Exhaustion

Once an iterator is exhausted, it cannot be reused without recreating it. For example:

12345678910
numbers = [1, 2, 3, 4] iterator = iter(numbers) # First iteration for num in iterator: print(num) # Output: 1, 2, 3, 4 # Second iteration for num in iterator: print(num) # Output: Nothing, the iterator is exhausted.
copy

Iterators can only be traversed once. To iterate again, a new iterator needs to be created.

Tarefa

Swipe to start coding

Complete the missing parts of the code to implement a custom iterator class for simulating an infinite die roller. The iterator should lazily generate random rolls of a six-sided die and stop after 10 rolls.

  1. The __iter__() method allows an object to be used as an iterator.
  2. The __next__() method produces the next random die roll (a number between 1 and 6).
  3. Create an instance of the InfiniteDie class, which represents the die roller.
  4. Use a for loop with enumerate() to roll the die lazily. Stop after 10 rolls using an if condition and the break statement.

Solução

Switch to desktopMude para o desktop para praticar no mundo realContinue de onde você está usando uma das opções abaixo
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 6. Capítulo 2
Switch to desktopMude para o desktop para praticar no mundo realContinue de onde você está usando uma das opções abaixo
Sentimos muito que algo saiu errado. O que aconteceu?
some-alt