← All lessons

Iterators: iter and next

Sign in · Sign up

Lesson 11.0

An iterator gives the items out one at a time, not the whole list at once.

numbers = [10, 20, 30]
it = iter(numbers)

print(next(it))   # 10
print(next(it))   # 20
print(next(it))   # 30
  • iter(list) creates an iterator;
  • next(iterator) gives the next item;
  • when the items run out, next raises a StopIteration.

A for loop works the same way inside: it creates the iterator itself and calls next until the StopIteration comes. An iterator cannot be indexed — it[0] won't work, and you can't loop over it a second time.

Write a function walk(numbers) that goes through the list with iter and next and returns the items one by one: the check collects them the same way a for loop does.

Hint

iter(list) gives an iterator, next(iterator) the next item.

For a function to hand items out one by one, it needs yield. No step counter is needed: the iterator remembers where it stopped.