Skip to main content

Implement linked list Iterators

Description

The provided code defines an iterable class that generates a sequence of numbers from 10 up to a specified limit using the __iter__ and __next__ methods. It demonstrates the implementation of a custom iterator in Python.

Code

program6a.py
class Iter:
def __init__(self, limit):
self.limit = limit

def __iter__(self):
self.x = 10
return self

def __next__(self):
x = self.x
if x > self.limit:
raise StopIteration
self.x = x + 1
return x

for i in Iter(13):
print(i)

Explanation of above code

Iter Class

  • The Iter class represents the iterator. It has three methods:
  • init(self, limit): This is the constructor method that initializes the iterator object. It takes a single parameter limit, which specifies the upper limit of the sequence. It assigns the limit to the self.limit attribute.
  • iter(self): This method is called when the iterator is initialized or reset. It returns the iterator object itself. In this case, it sets the starting value of the sequence to 10 by assigning self.x = 10.
  • next(self): This method is called to retrieve the next element in the sequence. It returns the next number in the sequence and advances the iterator. If the current number (self.x) exceeds the specified limit (self.limit), it raises a StopIteration exception to signal the end of the iteration. Otherwise, it increments self.x by 1 and returns the current number.

Iterating Over the Iterator

  • The code demonstrates the usage of the iterator by using it in a for loop:
  • Iter(13): An instance of the Iter class is created with a limit of 13. The limit determines the maximum value in the generated sequence.
  • for i in Iter(13): The for loop iterates over the Iter object, which automatically calls the iter method to initialize the iterator.
  • print(i): Inside the loop, each value generated by the iterator is printed. The loop continues until the StopIteration exception is raised, indicating the end of the iteration.
  • The output of this code will be a sequence of numbers starting from 10 and ending at 13:
  • 10
  • 11
  • 12
  • 13
  • The purpose of this code is to demonstrate how to implement a custom iterator in Python using the iter and next methods. It allows you to define your own iteration behavior for custom objects.

Learn more

Attention

Some students recommended that this below lecture is more easy to understand and it covers concepts of singly linked list in depth. So if anyone wants to check out the archived lecture that i recommended, check this out.

— Have a good day :)

Reference