iter()
Returns an iterator for a collection, an object that hands out its items one at a time. This is the mechanism behind the for loop.
- Returns
- An iterator.
Example
#lessons = ["Variables", "Loops", "Functions"]
it = iter(lessons)
print(next(it))
print(next(it))
print(list(it))
print(list(it))Definition and usage
#The iter(collection) function returns an iterator: an object that remembers how far it has gone and hands out the next item on request. You get further items with the next() function, and once they run out, the iterator raises a StopIteration exception.
A for loop does exactly this automatically: first it calls iter() on the collection, then next() until StopIteration. An object you can get an iterator from (a list, a string, a dictionary, a file, a range) is called an iterable. The iterator itself is single-use: once exhausted it stays empty, and calling iter() on it returns the very same object.
The second form, iter(function, sentinel), calls the function with no arguments until it returns a value equal to the sentinel. It's useful for reading data in chunks, for example from a file. Your own class becomes iterable once you give it an __iter__ method, most simply written as a generator with yield.
Syntax
#iter(iterable)
iter(callable, sentinel)Parameters
#iterable
an iterable object
A collection, or another object you can loop over with aforloop.callable
a function with no arguments
In the second form: a function called each time an item is fetched.sentinel
any value
The sentinel. Whencallablereturns it, the iterator ends, and the sentinel itself is not returned.
More examples
#scores = [72, 95, 64]
it = iter(scores)
while True:
try:
score = next(it)
except StopIteration:
break
print(score)
print(iter(it) is it)The while loop does step by step exactly what the short form for score in scores: does.
import io
stream = io.StringIO("1_1;1_2;1_3;1_4")
for chunk in iter(lambda: stream.read(4), ""):
print(chunk)io.StringIO stands in for a file here. With a file opened through open(), the code looks the same, and an empty string marks the end of the data.
class Course:
def __init__(self, title, lessons):
self.title = title
self.lessons = lessons
def __iter__(self):
for number, lesson in enumerate(self.lessons, start=1):
yield f"{number}. {lesson}"
python = Course("Python", ["Variables", "Loops"])
for line in python:
print(line)
print(list(python))Good practices
#- An iterator can only be walked through once. If you need the data several times, store it in a list or create a new iterator.
- You don't need to call
iter()before aforloop. It becomes useful once you want to fetch items by hand withnext(), for example to skip a header. - An
__iter__method written as a generator returns a new iterator on every call, so you can loop over such an object several times.
Related entries
#- next()Fetches the next item from an iterator. Once it is exhausted, returns a default value or raises StopIteration.
- forA loop that goes through the successive items of a sequence or other iterable object.
- yieldCreates a generator: a function that returns successive values on demand.
- enumerate()Adds a counter to items while looping over them.
Spotted a mistake or missing an example? Write to us.