Fundamentals 5 min read

Understanding Python's iter() Function, Iterators, and Generators

This article explains Python's iter() function, its syntax with optional sentinel argument, demonstrates creating iterators from lists and callable objects, and explores the roles of __iter__ and __next__ methods and generator functions through clear code examples.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Understanding Python's iter() Function, Iterators, and Generators

The iter() function creates an iterator from an iterable object; it can also accept a second sentinel argument, in which case the first argument must be a callable that is invoked repeatedly until the sentinel value is returned.

Syntax: iter(object[, sentinel]) . The object parameter is any iterable (e.g., list, set, dict). If sentinel is provided, object must be callable.

Example 1 – iterating a list:

lst = [1, 2, 3]
for i in iter(lst):
    print(i)
# 1
# 2
# 3

Example 2 – using a sentinel with a callable: The iterator calls the callable without arguments; when the callable returns a value equal to the sentinel, StopIteration is raised.

class counter:
    def __init__(self, _start, _end):
        self.start = _start
        self.end = _end
    def get_next(self):
        s = self.start
        if self.start < self.end:
            self.start += 1
        else:
            raise StopIteration
        return s
c = counter(1, 5)
iterator = iter(c.get_next, 3)
print(type(iterator))  #
for i in iterator:
    print(i)
# 1
# 2

The __iter__ method returns the iterator object (often self ), while __next__ produces the next value or raises StopIteration . A class defining both methods is iterable and can be used directly in a for loop.

class test:
    def __init__(self, data=1):
        self.data = data
    def __iter__(self):
        return self
    def __next__(self):
        if self.data > 5:
            raise StopIteration
        else:
            self.data += 1
        return self.data
for item in test(3):
    print(item)
# 4
# 5
# 6

Generators are a special kind of iterator defined with the yield statement. Calling a generator function returns a generator object that produces values lazily.

def fib(end=1000):
    prev, curr = 0, 1
    while curr < end:
        yield curr
        prev, curr = curr, curr + prev
print(list(fib()))
# [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]

Feel free to share the QR code, thank you!

PythoniteratorsSentinelGenerators__iter__nextcallable_iterator
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.