Use iter() and next()

EasyIterator & Generator Programs · 1 of 20

Write a Python program that walks through a list with iter() and next().

Advertisement
Output
login
search
logout
no more steps

Approach

  1. next() returns items one by one; a default avoids StopIteration.

Solution

Python
it = iter(["login", "search", "logout"])print(next(it))print(next(it))print(next(it))print(next(it, "no more steps"))
Output
login
search
logout
no more steps

Learn the concept

New to this topic? Read the lesson, then come back.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Leave a Comment