Built-in function

iter()

Returns an iterator, an object that hands out the items of a list, string or file one at a time each time you call next() on it.

IntermediateEvery example below runs in your browser. Change the code and press Run.

iter(object) iter(callable, sentinel)

An iterator is an object that remembers where it is in a collection. Each call to next() gives the next item, and when there are no items left it raises StopIteration. iter() makes an iterator from anything you can loop over.

Every for loop calls iter() for you behind the scenes, so you rarely need it in simple code. It becomes useful when you want to take items by hand: skip a header line, read items in pairs, or stop and continue later.

An iterator can be used only once. When it reaches the end it stays empty, while the list it came from is unchanged and can give you a fresh iterator.

The two-argument form iter(func, sentinel) calls func() again and again and stops when it returns the sentinel value.

Parameters

ParameterWhat it is
object
required
Something you can loop over: a list, tuple, string, dict, set, file...
sentinel
optional
Only in the second form. The first argument must then be a function with no arguments; iteration stops when it returns this value.

Return value

An iterator object. Pass it to next() or loop over it.

Examples

1Take items one at a time

Pythoneditable
colors = ["red", "green", "blue"]
it = iter(colors)
print(next(it))
print(next(it))
print(next(it))
print(next(it, "no more"))
Output
red
green
blue
no more

2What a for loop does behind the scenes

Pythoneditable
it = iter("abc")
while True:
    try:
        letter = next(it)
    except StopIteration:
        break
    print(letter.upper())
Output
A
B
C

This is exactly how for letter in "abc": works inside.

3An iterator is used up after one pass

Pythoneditable
numbers = [1, 2, 3]
it = iter(numbers)
print(list(it))
print(list(it))
print(list(numbers))
Output
[1, 2, 3]
[]
[1, 2, 3]

4Group items in pairs

zip() takes one item from each argument in turn. Giving it the same iterator twice pulls two items in a row.

Pythoneditable
values = ["Ana", 31, "Ben", 27, "Cleo", 45]
it = iter(values)
for name, age in zip(it, it):
    print(name, "is", age)
Output
Ana is 31
Ben is 27
Cleo is 45

5Read lines until a blank line with iter(func, sentinel)

f.readline is called again and again until it returns a line that is just "\n": the empty line between the headers and the message.

Pythoneditable
with open("email.txt", encoding="utf-8") as f:
    for line in iter(f.readline, "\n"):
        print("Header:", line.strip())
    print("Body:", f.read().strip())
Output
Header: From: Omar
Header: Subject: Lunch
Body: See you at noon.

Common mistakes

Calling iter() on something you cannot loop over

Numbers are not collections, so iter(5) raises TypeError. Use range(5) if you wanted the numbers 0 to 4.

Pythoneditable
try:
    iter(5)
except TypeError:
    print("TypeError: a number is not iterable")
print(list(iter(range(5))))
Output
TypeError: a number is not iterable
[0, 1, 2, 3, 4]

Looping over the same iterator twice

If you store it = iter(data) and loop over it twice, the second loop gets nothing. Loop over the list itself, or call iter() again.

Questions people ask

What is the difference between an iterable and an iterator?

An iterable (a list, a string) can be looped over many times. An iterator is the one-time cursor you get from iter(iterable): it moves forward with next() and cannot go back.

How do I check if something is iterable?

Try it: try: iter(x) and catch TypeError. This works for every kind of iterable.

How do I make my own class iterable?

Give it an __iter__ method that returns an iterator. The easiest way is to write __iter__ as a generator with yield.

Spotted a mistake on this page? Tell us