CodingNic

Intermediate Python

Iterators

Intermediate Python 30 min read

Iterators

Iterators

You have used loops many times.

Example:

python
for item in [1, 2, 3]:
    print(item)

But have you ever wondered how Python gets one item at a time?

It uses iterators.

What Is an Iterator?

An iterator is an object that gives values one at a time.

Instead of returning everything at once, it returns the next item when asked.

Why Iterators Matter

Iterators help Python:

  • run for loops
  • process data step by step
  • save memory
  • work with large data

Iterable vs Iterator

Iterable

An iterable is something you can loop through.

Examples:

  • list
  • tuple
  • string
  • dictionary
  • set

Iterator

An iterator is what Python uses behind the scenes to get values one by one.

Create an Iterator

Use iter().

python
numbers = [10, 20, 30]

it = iter(numbers)

print(it)

Example Output

text
<list_iterator object at ...>

Get Values with next()

Use next() to get the next item.

python
numbers = [10, 20, 30]

it = iter(numbers)

print(next(it))
print(next(it))
print(next(it))

Output

text
10
20
30

What Happens After the Last Item?

python
print(next(it))

Python raises:

text
StopIteration

This means there are no more values.

How for Loop Uses Iterators

This loop:

python
for number in [1, 2, 3]:
    print(number)

Works like this idea:

python
it = iter([1, 2, 3])

print(next(it))
print(next(it))
print(next(it))

Iterator with String

python
text = "ABC"

it = iter(text)

print(next(it))
print(next(it))
print(next(it))

Output

text
A
B
C

Safe next()

Use a default value.

python
numbers = [1]

it = iter(numbers)

print(next(it, "Done"))
print(next(it, "Done"))

Output

text
1
Done

Code Along

Create an iterator from:

python
["Pen", "Book", "Bag"]

Use next() three times.

Mini Challenge

Create an iterator from:

python
(5, 10, 15)

Tasks:

  • Print first value
  • Print second value
  • Print third value

Expected output:

text
5
10
15

Real World Use Case

Iterators are used in loops, files, generators, data streams, and large datasets.

Quiz

  1. What is an iterator?
  2. What is the difference between iterable and iterator?
  3. What does next() do?
  4. What error happens when values are finished?

Assignment

Create an iterator from a string and print each character using next().

Summary

You learned how iterators return values one at a time and power Python loops.