Iterate over collections
Process a collection lazily without indexing or copying it.
Python · Function
iter() returns an iterator for an iterable object, or repeatedly invokes a callable until its result equals a supplied sentinel. It supports both protocol-based iteration and callable-driven iteration.
iter() produces an iterator from an iterable object, such as a list or dictionary. With a callable and a sentinel, it repeatedly calls the callable and stops when the returned value equals the sentinel.
iter(object, sentinel, /)| Name | Type | Description |
|---|---|---|
object | object | An iterable object, or a callable when sentinel is supplied. |
sentinel | object | A stopping value used with callable; iteration ends when a call returns it. |
An iterator object.
__iter__() method.TypeError.values = [10, 20, 30]
iterator = iter(values)
print(next(iterator))
print(list(iterator))
Creates an iterator from a list, consumes its first item explicitly, then collects the remaining items.
Process a collection lazily without indexing or copying it.
Read successive values from a producer until a designated end value appears.
Consume a custom object that implements Python’s iterable or sequence protocol.
iter() accept?iter(object) returns an iterator for an object supporting the iterable protocol through __iter__(), or the sequence protocol through integer __getitem__() calls starting at zero. The iterator then supplies values one at a time.
Follow-up: What does iter(callable, sentinel) do? It repeatedly calls the callable and stops when its result compares equal to the sentinel.
The two-argument form calls the first argument repeatedly and returns an iterator over those results. Iteration ends when a result equals the sentinel value.
Follow-up: Why is this useful for reading fixed-size chunks? A callable can fetch one chunk per iteration, while an empty chunk sentinel terminates the loop.
iter()?iter() returns an iterator object, which is consumed by operations such as next() and for. Once exhausted, subsequent retrieval attempts follow normal iterator exhaustion behavior.
Follow-up: How can a loop avoid manually handling exhaustion? A for loop repeatedly requests values and stops when the iterator is exhausted.
next()aiter()anext()__iter__()__getitem__()