Python Reference ยท Built-in Functions
Python iter() function
Reference for Python iter(): get an iterator from an iterable, the two-argument sentinel form, iterators being exhausted, and how it pairs with next().
The iter() function returns an iterator for an object. An iterator is something you can step through one item at a time with next(); when it has no more items, it raises StopIteration. A for loop calls iter() on its target behind the scenes.
With one argument, iter() asks the object for its iterator. With two arguments it builds an iterator that keeps calling a function until the function returns a special "stop" value.
it = iter([10, 20]) print(next(it), next(it)) # 10 20
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
iter(object) iter(callable, sentinel)
| Name | Description |
|---|---|
object |
An iterable (has __iter__()), or a sequence that supports __getitem__() with integer indexes starting at 0. |
callable |
A function called with no arguments for each item. |
sentinel |
The value that ends iteration; compared with ==. It is not produced as an item. |
Return value: an iterator object.
Raises: TypeError if the object is not iterable, or if callable in the two-argument form is not callable.
Usage notes
- Iterables vs iterators. A list is iterable but is not an iterator: each
iter(my_list)call returns a new, independent iterator. An iterator returns itself fromiter(). - Iterators are single-use. Once exhausted they stay empty. If you need two passes, keep the original iterable or use
itertools.tee(). next()with a default avoidsStopIteration:next(it, None).- Old-style sequences. Objects with only
__getitem__()still work; Python tries index 0, 1, 2 and stops atIndexError. - Two-argument form is the classic way to read until a marker, for example
iter(lambda: f.read(4096), b"")to read a file in chunks. - Shared state. Two names bound to the same iterator advance together, which surprises people who pass an iterator to two consumers.
- Custom classes. Implement
__iter__()(and__next__()for an iterator), or write a generator function. See iterators and generators.