Python 3 reference · Built-in Functions
Python iter() Function
Get an iterator from an iterable, or create one that calls a function until it returns a sentinel value.
Python 3 Since 3.0
Syntax
iter(iterable)
iter(callable, sentinel)
Parameters
| Parameter | Description |
|---|---|
iterable |
Any iterable. |
callable, sentinel optional |
Call callable() repeatedly until it returns sentinel. |
Return value
An iterator.
Examples
it = iter([10, 20, 30])
print(next(it), next(it), next(it))
print(next(it, "no more"))
Output
10 20 30 no more
import io
stream = io.StringIO("abcdefgh")
for chunk in iter(lambda: stream.read(3), ""):
print(chunk)
Output
abc def gh
Good to know
An iterator can be used once: after it is exhausted, it stays empty. Call iter() on the original
iterable again to start over.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
next()· Get the next item from an iterator. When it is exhausted, return the default if given, otherwise raise StopIteration.aiter()· Return an asynchronous iterator for an async iterable: the async counterpart of iter(), used with async for and anext().enumerate()· Loop over an iterable and get each item together with its index, as (index, item) pairs. The start number is configurable.reversed()· Return an iterator that goes through a sequence backwards, without copying it. Works on lists, tuples, strings and ranges.- Python Iterators and Generators · tutorial