iter()

The built-in iter() function creates an iterator object from an iterable. This function facilitates traversing the elements of a container, such as lists, tuples, dictionaries, and sets, by returning an iterator:

Python
>>> colors = ["red", "orange", "yellow", "green"]
>>> colors_it = iter(colors)
>>> colors_it
<list_iterator object at 0x1070e2c20>

>>> for color in colors_it:
...     print(color)
...
red
orange
yellow
green

iter() Signature

Python Syntax
iter(iterable)
iter(object, sentinel)

Arguments

Argument Description
iterable An object capable of returning its members one at a time. It must implement either the .__iter__() or the .__getitem__() special method.
object A callable object that is used with the sentinel value to create an iterator that calls the object until the sentinel value is returned.
sentinel A value that, when returned from the callable object, causes the iterator to raise a StopIteration exception.

Return Value

  • When called with an iterable, iter() returns an iterator object that can traverse the elements of the iterable.
  • When called with an object and sentinel, it returns an iterator that calls object until the sentinel value is returned.

iter() Examples

With an iterable like a list:

Python
>>> numbers = [1, 2, 3]
>>> num_iter = iter(numbers)
>>> next(num_iter)
1

With a callable object and a sentinel value:

Python
>>> from random import randint

>>> rand_it = iter(lambda: randint(1, 10), 7)
>>> next(rand_it)
9
>>> next(rand_it)
5
>>> next(rand_it)
5
>>> next(rand_it)
6
>>> next(rand_it)
Traceback (most recent call last):
    ...
StopIteration

iter() Common Use Cases

The most common use cases for the iter() function include:

  • Iterating over elements of a collection like lists, tuples, sets, and dictionaries.
  • Creating custom iterators using callables and sentinel values.

iter() Real-World Example

Imagine you have a CLI application that processes user input until the user enters "exit". You can use iter() with the built-in input() function to handle this scenario:

Python
>>> def process_input():
...     for command in iter(lambda: input("Enter command: "), "exit"):
...         print(f"Executing: {command}")
...

>>> process_input()
Enter command: list
Executing: list
Enter command: add
Executing: add
Enter command: exit

In this example, iter() helps you by repeatedly calling input() until the user types "exit", at which point the iteration stops.

iter() in Custom Classes

You can support iter() in your custom classes by providing an .__iter__() method that returns an iterator object. For example, say that you have a Stack class and want to make it iterable:

Python
class Stack:
    def __init__(self):
        self._items = []

    def push(self, item):
        self._items.append(item)

    def pop(self):
        try:
            return self._items.pop()
        except IndexError:
            raise IndexError("pop from an empty stack") from None

    def __iter__(self):
        yield from self._items

# Usage
stack = Stack()
stack.push(1)
stack.push(2)

stack_it = iter(stack)
print(stack_it) # Output: <list_iterator object at 0x106233010>
print(next(stack_it))  # Output: 1
print(next(stack_it))  # Output: 2

Your class has an .__iter__() method that returns an iterator using the yield from construct. You can use instances of your class as arguments to iter().

Tutorial

Iterators and Iterables in Python: Run Efficient Iterations

In this tutorial, you'll learn what iterators and iterables are in Python. You'll learn how they differ and when to use them in your code. You'll also learn how to create your own iterators and iterables to make data processing more efficient.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 22, 2024 • Reviewed by Dan Bader