+91 81900 98289

Python Iterators

This Python Iterators lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

An iterator remembers where it is in a stream of values. iter builds one. next asks for the following value.

A for loop calls those steps for you. You write next yourself when you want one value at a time.

Example 1: Start here

Asking past the end raises StopIteration.

names = iter(["Meera", "Arun"]) # a walker that gives one value at a time print(next(names)) print(next(names))

Example 2: Next pulls one item

iter starts the iterator. next returns one item and moves forward.

skills = iter(["Python", "SQL"]) # a walker that gives one value at a time print(next(skills)) print(next(skills))

Example 3: A for loop uses the iterator

A for loop calls next for you and stops at the end.

for skill in ["Python", "SQL"]: # repeat the indented lines once per value print(skill)

Example 4: A default at the end

The second argument of next is returned when there is nothing left.

skills = iter(["Python"]) # a walker that gives one value at a time print(next(skills, "done")) print(next(skills, "done"))
Asking past the end raises StopIteration.
Call Now 81900 98289