Python iter() - Create Iterator

Updated on September 27, 2024
iter() header image

Introduction

The iter() function in Python is a built-in function that returns an iterator for the given object, which then allows you to iterate over its elements one at a time. This function plays a fundamental role in Python, especially in building and working with loops that process elements of a collection sequentially without accessing them by index.

In this article, you will learn how to effectively use the iter() function to create iterators from various iterable objects such as lists, tuples, and custom objects. Explore how to customize iteration behavior using callable objects and sentinel values, enriching your understanding of Python's iteration protocols.

Using iter() with Built-in Types

Create an Iterator from a List

  1. Create a list of elements.

  2. Use the iter() function to convert the list into an iterator.

  3. Loop through the iterator using a for loop to access each element.

    python
    fruit_list = ['apple', 'banana', 'cherry']
    fruit_iterator = iter(fruit_list)
    for fruit in fruit_iterator:
        print(fruit)
    

    This code converts the list fruit_list into an iterator and prints each item. Each iteration of the loop retrieves the next element from the iterator until no elements are left.

Convert a Tuple into an Iterator

  1. Define a tuple containing multiple elements.

  2. Convert the tuple into an iterator.

  3. Iterate over the tuple using a for loop.

    python
    number_tuple = (1, 2, 3, 4)
    tuple_iterator = iter(number_tuple)
    for number in tuple_iterator:
        print(number)
    

    Here, the tuple number_tuple is transformed into an iterator, and every item in the tuple is accessed sequentially and printed.

Custom Iteration with Callable and Sentinel

Use Callable and Sentinel to Control Iteration

  1. Define a callable that generates output.

  2. Specify a sentinel value that, when returned by the callable, will end the iteration.

  3. Use the iter() function with both the callable and the sentinel to create a customized iterator.

  4. Iterate over the results until the sentinel stops the iteration.

    python
    import random
    
    def generate_random():
        return random.randint(1, 10)
    
    # Create iterator with a sentinel value of 5
    random_iterator = iter(generate_random, 5)
    for number in random_iterator:
        print(number)
    

    This example generates random numbers between 1 and 10 and uses 5 as a sentinel. The iteration stops when 5 is generated. Each random number different from 5 is printed.

Implementing Iterable Class Using iter()

  1. Design a class that implements both __iter__() and __next__() methods to make it iterable.

  2. Use iter() implicitly when iterating over an instance of the class.

    python
    class CountDown:
        def __init__(self, start):
            self.current = start
        def __iter__(self):
            return self
        def __next__(self):
            if self.current <= 0:
                raise StopIteration
            else:
                num = self.current
                self.current -= 1
                return num
    
    # Create an instance and use for loop to iterate
    countdown = CountDown(5)
    for number in countdown:
        print(number)
    

    In this example, a CountDown class is defined that counts down from a starting number. It becomes iterable by defining the __iter__() and __next__() methods, making the use of iter() implied in the for loop.

Conclusion

The iter() function is indispensable in Python for creating iterators from iterable objects and for allowing fine control over iteration processes with custom behavior through callable and sentinel. By mastering the use of iter(), you significantly enhance the flexibility and readability of your Python programming, especially when dealing with complex looping scenarios and custom sequence types. Utilize these techniques to simplify and optimize your iteration logic in projects.