Skip to content

Module 10 · Comprehensions and Advanced Iteration — topic 9 of 13

iter()

Getting an iterator from any iterable with iter(), using a shared iterator to consume data in chunks, and the two-argument form iter(callable, sentinel).

Beginner 8 min read·Lesson 153 of 306 in Python Programming

Learning objectives

  • Create iterators with iter()
  • Use one iterator in several places to share progress
  • Use the sentinel form of iter() for read-until loops

Definition

The built-in iter(obj) returns an iterator for an iterable object. The two-argument form iter(callable, sentinel) returns an iterator that calls callable() repeatedly until it returns the sentinel value.

Introduction

Usually for loops call iter() for you. Calling it yourself is useful when you want to control iteration: skip a header, take items in pairs, or read until a special value appears.

Why it matters

Explicit iterators make some tasks elegant — reading a file header, grouping a flat list into pairs — that are clumsy with indexes.

Detailed explanation

iter(iterable) returns a new iterator. If the object isn't iterable, it raises TypeError.

Because an iterator remembers its position, you can consume part of it with next() and pass the rest to a for loop or a function.

zip(it, it) with the same iterator twice takes consecutive pairs: each zip step pulls two values from the one iterator.

iter(callable, sentinel) repeatedly calls a zero-argument function and stops when it returns sentinel — a clean replacement for while True loops that read until an end marker.

next(iterator, default) returns default instead of raising StopIteration when the iterator is exhausted.

Syntax

Python
it = iter(lines)
header = next(it) # take the first item
for line in it: ... # loop over the rest
pairs = list(zip(it, it)) # consecutive pairs
for block in iter(lambda: f.read(1024), ""): ...
  • iter(x) returns an iterator.
  • Sharing one iterator shares the position.
  • iter(f, sentinel) stops at the sentinel.

Code examples

Skipping a header

Python
rows = ["name,marks", "Asha,91", "Ravi,74"]
it = iter(rows)
header = next(it).split(",")
for row in it:
print(dict(zip(header, row.split(","))))
Output
{'name': 'Asha', 'marks': '91'}
{'name': 'Ravi', 'marks': '74'}

Pairs from a flat list

Python
flat = ["pen", 20, "book", 350, "bag", 1200]
it = iter(flat)
print(dict(zip(it, it)))
Output
{'pen': 20, 'book': 350, 'bag': 1200}

More examples

The sentinel form

Python
commands = ["add 5", "add 7", "sub 2", "quit", "add 100"]
feed = iter(commands)
read_command = lambda: next(feed)
total = 0
for cmd in iter(read_command, "quit"):
op, value = cmd.split()
total += int(value) if op == "add" else -int(value)
print(total)
print(next(feed), next(feed, "no more"))
Output
10
add 100 no more

Step-by-step explanation

  • read_command simulates reading one command, for example from input().
  • iter(read_command, "quit") calls it repeatedly and stops as soon as it returns "quit".
  • 5 + 7 − 2 gives 10; the sentinel itself is consumed but not processed.
  • The underlying iterator continues after the sentinel, and next(feed, default) avoids StopIteration at the end.

Expected output

Running “The sentinel form” prints exactly:

TextOutput
10
add 100 no more

Practical applications

  • Reading a file in fixed-size blocks: iter(lambda: f.read(4096), b'').
  • Reading input lines until the user types 'done'.

Best practices

  • Use next(it, default) when the iterator may be empty.
  • Use the sentinel form instead of while True with a break.
  • Keep one explicit iterator when you need to share position.

Common mistakes

Creating a new iterator each time

Avoid

header = next(iter(rows))
for row in iter(rows): ... # starts again at the header

Prefer

it = iter(rows)
header = next(it)
for row in it: ...

Each iter(list) starts from the beginning; keep one iterator to share progress.

Important notes

  • itertools.batched (Python 3.12+) groups items into tuples of n, a general version of the zip(it, it) trick.

Key takeaways

  • iter(iterable) returns an iterator.
  • A shared iterator shares its position.
  • iter(callable, sentinel) loops until the sentinel appears.

Try it yourself

  1. 1
    Group a list of 9 numbers into triples using one iterator and zip.
  2. 2
    Read numbers with input() until the user enters an empty line, using iter(input, '').

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions cover the “Comprehensions and Advanced Iteration” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module