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

Contenido del Curso

Python Advanced Concepts

Python Advanced Concepts

1. Modules and Imports
2. Error Handling
3. File Handling
4. Pytest Framework
5. Unittest Framework
6. Iterators and Generators

bookUnderstanding Iterators

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.

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

Suppose you want to process only even IDs from a sequence. Instead of filtering the entire dataset upfront, you can create a custom iterator to yield only even numbers dynamically.

12345678910111213141516171819202122
class EvenIDIterator: def __init__(self, ids): self.ids = ids self.index = 0 def __iter__(self): return self def __next__(self): while self.index < len(self.ids): id = self.ids[self.index] self.index += 1 if id % 2 == 0: return id raise StopIteration # Using the custom iterator ids = [101, 102, 103, 104, 105] even_ids = EvenIDIterator(ids) for id in even_ids: print(f"Even ID: {id}")
copy

Explanation:

  • __next__() skips odd IDs and returns only even IDs;
  • The StopIteration exception is raised when all elements are processed.

Iterators vs. Iterables

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.

Tarea
test

Swipe to show code editor

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.

Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 6. Capítulo 2
toggle bottom row

bookUnderstanding Iterators

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.

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

Suppose you want to process only even IDs from a sequence. Instead of filtering the entire dataset upfront, you can create a custom iterator to yield only even numbers dynamically.

12345678910111213141516171819202122
class EvenIDIterator: def __init__(self, ids): self.ids = ids self.index = 0 def __iter__(self): return self def __next__(self): while self.index < len(self.ids): id = self.ids[self.index] self.index += 1 if id % 2 == 0: return id raise StopIteration # Using the custom iterator ids = [101, 102, 103, 104, 105] even_ids = EvenIDIterator(ids) for id in even_ids: print(f"Even ID: {id}")
copy

Explanation:

  • __next__() skips odd IDs and returns only even IDs;
  • The StopIteration exception is raised when all elements are processed.

Iterators vs. Iterables

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.

Tarea
test

Swipe to show code editor

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.

Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 6. Capítulo 2
toggle bottom row

bookUnderstanding Iterators

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.

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

Suppose you want to process only even IDs from a sequence. Instead of filtering the entire dataset upfront, you can create a custom iterator to yield only even numbers dynamically.

12345678910111213141516171819202122
class EvenIDIterator: def __init__(self, ids): self.ids = ids self.index = 0 def __iter__(self): return self def __next__(self): while self.index < len(self.ids): id = self.ids[self.index] self.index += 1 if id % 2 == 0: return id raise StopIteration # Using the custom iterator ids = [101, 102, 103, 104, 105] even_ids = EvenIDIterator(ids) for id in even_ids: print(f"Even ID: {id}")
copy

Explanation:

  • __next__() skips odd IDs and returns only even IDs;
  • The StopIteration exception is raised when all elements are processed.

Iterators vs. Iterables

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.

Tarea
test

Swipe to show code editor

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.

Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

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.

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

Suppose you want to process only even IDs from a sequence. Instead of filtering the entire dataset upfront, you can create a custom iterator to yield only even numbers dynamically.

12345678910111213141516171819202122
class EvenIDIterator: def __init__(self, ids): self.ids = ids self.index = 0 def __iter__(self): return self def __next__(self): while self.index < len(self.ids): id = self.ids[self.index] self.index += 1 if id % 2 == 0: return id raise StopIteration # Using the custom iterator ids = [101, 102, 103, 104, 105] even_ids = EvenIDIterator(ids) for id in even_ids: print(f"Even ID: {id}")
copy

Explanation:

  • __next__() skips odd IDs and returns only even IDs;
  • The StopIteration exception is raised when all elements are processed.

Iterators vs. Iterables

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.

Tarea
test

Swipe to show code editor

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.

Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
Sección 6. Capítulo 2
Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
We're sorry to hear that something went wrong. What happened?
some-alt