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.
On this page

Example

#
Python
lessons = ["Variables", "Loops", "Functions"]
it = iter(lessons)

print(next(it))
print(next(it))
print(list(it))
print(list(it))
Resultsaved result, you can check it
Variables
Loops
['Functions']
[]

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

#
Syntax
iter(iterable)
iter(callable, sentinel)

Parameters

#
  • iterable

    an iterable object

    A collection, or another object you can loop over with a for loop.
  • callable

    a function with no arguments

    In the second form: a function called each time an item is fetched.
  • sentinel

    any value

    The sentinel. When callable returns it, the iterator ends, and the sentinel itself is not returned.

More examples

#
This is how a for loop works
Python
scores = [72, 95, 64]
it = iter(scores)

while True:
    try:
        score = next(it)
    except StopIteration:
        break
    print(score)

print(iter(it) is it)
Resultsaved result, you can check it
72
95
64
True

The while loop does step by step exactly what the short form for score in scores: does.

Reading in chunks with a sentinel
Python
import io

stream = io.StringIO("1_1;1_2;1_3;1_4")
for chunk in iter(lambda: stream.read(4), ""):
    print(chunk)
Resultsaved result, you can check it
1_1;
1_2;
1_3;
1_4

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.

A custom class in a for loop
Python
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))
Resultsaved result, you can check it
1. Variables
2. Loops
['1. Variables', '2. Loops']

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 a for loop. It becomes useful once you want to fetch items by hand with next(), 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

#

Spotted a mistake or missing an example? Write to us.