Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Iterator Pattern

Python Iterator Pattern

Imagine you have a jar full of candies of various colors. You want to taste them one by one, but you don't want to pour them all out at once. In that case, you reach into the jar and take out one candy at a time - this process is iteration.

In programming,Iterator Pattern is a design pattern that provides a way to sequentially access the individual elements of a collection object without exposing its internal representation.

Core Concepts

The iterator pattern consists of two main components:

  1. Iterator: Responsible for defining the interface for accessing and traversing elements
  2. Iterable: Provides a method for creating an iterator

In Python, the iterator pattern is deeply integrated into the language's core features, making our programming more elegant and intuitive.


Why Do We Need Iterators?

Limitations of the Traditional Approach

Let's first look at an example that does not use iterators:

Example

A simple book collection class

class

BookCollection:

   

def

init

(

self

)

:

       

self

.

books

=

[

"Python Intro"

,

"Introduction to Algorithms"

,

"Design Patterns"

,

"Data Structures"

]

   

   

def

get_books

(

self

)

:

       

return

self

.

books

Using this collection

collection

=

BookCollection

(

)

books

=

collection.

get_books

(

)

Iterating over books - Exposing internal implementation details

for

i

in

range

(

len

(

books

)

)

:

   

print

(

books

[

i

]

)

Problem Analysis:

Advantages of Iterators

Example

The way of using iterators

for

book

in

collection:

   

print

(

book

)

Benefits brought by iterators:


The Iterator Protocol in Python

Python implements the iterator protocol through two special methods:

__iter__() Method

__next__() Method

Let's understand how iterators work through a flowchart:


Creating a Custom Iterator

Method 1: Implementing an Iterator Using a Class

Let's create a custom book iterator:

Example

class

BookIterator:

   

"""Book iterator class"""

   

   

def

init

(

self

,

books

)

:

       

self

.

books

=

books

       

self

.

index

=

0

   

   

def

iter

(

self

)

:

       

"""Return the iterator itself"""

       

return

self

   

   

def

next

(

self

)

:

       

"""Return the next book; if there are no more books, raise StopIteration"""

       

if

self

.

index

<

len

(

self

.

books

)

:

            book

=

self

.

books

[

self

.

index

]

           

self

.

index

=

1

           

return

book

       

else

:

           

raise

StopIteration

class

BookCollection:

   

"""Iterable book collection class"""

   

   

def

init

(

self

)

:

       

self

.

books

=

[

"Python Intro"

,

"Introduction to Algorithms"

,

"Design Patterns"

,

"Data Structures"

]

   

   

def

iter

(

self

)

:

       

"""Return an iterator instance"""

       

return

BookIterator

(

self

.

books

)

Using the Custom Iterator

collection

=

BookCollection

(

)

for

book

in

collection:

   

print

(

f

"Reading: {book}"

)

Output result:

正在阅读: Python入门
正在阅读: 算法导论
正在阅读: 设计模式
正在阅读: 数据结构

Method 2: Using Generator Functions

Python provides a more concise approach - generator functions:

Example

class

BookCollection:

   

def

init

(

self

)

:

       

self

.

books

=

[

"Python Intro"

,

"Introduction to Algorithms"

,

"Design Patterns"

,

"Data Structures"

]

   

   

def

iter

(

self

)

:

       

"""Create an iterator using a generator function"""

       

for

book

in

self

.

books

:

           

yield

book

Used in exactly the same way

collection

=

BookCollection

(

)

for

book

in

collection:

   

print

(

f

"Reading: {book}"

)

Advantages of Generators:


Practical Application Scenarios of Iterators

Scenario 1: Paginated Data Reading

Example

class

PaginatedData:

   

"""Simulated paginated data iterator"""

   

   

def

init

(

self

,

total_items

,

page_size

=

3

)

:

       

self

.

total_items

=

total_items

       

self

.

page_size

=

page_size

       

self

.

current_page

=

0

   

   

def

iter

(

self

)

:

       

return

self

   

   

def

next

(

self

)

:

        start

=

self

.

current_page

self

.

page_size

        end

=

start +

self

.

page_size

       

       

if

start

=

self

.

total_items

:

           

raise

StopIteration

       

       

Simulating reading a page of data from a database

        page_data

=

list

(

range

(

start

,

min

(

end

,

self

.

total_items

)

)

)

       

self

.

current_page

=

1

       

       

return

page_data

Using the paginated iterator

paginator

=

PaginatedData

(

10

,

3

)

 

A total of 10 records, 3 per page

for

page_num

,

page_data

in

enumerate

(

paginator

,

1

)

:

   

print

(

f

"Page {page_num} data: {page_data}"

)

Output result:

第1页数据: [0, 1, 2]
第2页数据: [3, 4, 5]
第3页数据: [6, 7, 8]
第4页数据: [9]

Scenario 2: Infinite Sequence Generation

Example

class

FibonacciIterator:

   

"""Fibonacci sequence iterator"""

   

   

def

init

(

self

,

max_count

=

10

)

:

       

self

.

max_count

=

max_count

       

self

.

count

=

0

       

self

.

a

,

self

.

b

=

0

,

1

   

   

def

iter

(

self

)

:

       

return

self

   

   

def

next

(

self

)

:

       

if

self

.

count

=

self

.

max_count

:

           

raise

StopIteration

       

        result

=

self

.

a

       

self

.

a

,

self

.

b

=

self

.

b

,

self

.

a

self

.

b

       

self

.

count

=

1

       

return

result

Generate the Fibonacci sequence

fib

=

FibonacciIterator

(

8

)

print

(

"Fibonacci sequence:"

,

list

(

fib

)

)

Output result:

斐波那契数列: [0, 1, 1, 2, 3, 5, 8, 13]

Built-in Iterator Tools

Python provides a rich set of built-in functions to work with iterators:

iter() and next() function

Example

numbers

=

[

1

,

2

,

3

,

4

,

5

]

Using an iterator manually

iterator

=

iter

(

numbers

)

print

(

next

(

iterator

)

)

 

Output: 1

print

(

next

(

iterator

)

)

 

Output: 2

print

(

next

(

iterator

)

)

 

Output: 3

enumerate() function

Example

fruits

=

[

'apple'

,

'banana'

,

'orange'

]

for

index

,

fruit

in

enumerate

(

fruits

)

:

   

print

(

f

"Index {index}: {fruit}"

)

zip() function

Example

names

=

[

'Alice'

,

'Bob'

,

'Charlie'

]

scores

=

[

85

,

92

,

78

]

for

name

,

score

in

zip

(

names

,

scores

)

:

   

print

(

f

"{name} score: {score}"

)


Iterator vs Iterable

It is important to understand the difference between these two concepts:

Feature Iterable Iterator
define implements the __iter__() Object with the method implements the __iter__() and __next__() Object with the method
Purpose Can be iterated over Actually performs the iteration operation
State Usually stateless Maintains iteration state (current position, etc.)
Example Lists, tuples, dictionaries, strings iter() The returned object

Relationship Diagram

Example

graph TD

    A[Iterable] -->|calling iter| B[Iterator]

    B -->|repeatedly calling next| C[element by element]

    C --> D[until StopIteration]


Best Practices and Common Mistakes

Best Practices

  1. Use generators to simplify code

Example

Recommended: Use generators

def

countdown

(

n

)

:

   

while

n

0

:

       

yield

n

        n -

=

1

Not recommended: Manually implementing iterator classes

  1. Make use of built-in functions

Example

Recommend

squares

=

(

x*x

for

x

in

range

(

10

)

)

 

Generator expressions

Not recommended

class

SquareIterator:

   

... Verbose implementation

Common mistakes

Mistake 1: Confusing Iterators and Iterables

Example

numbers

=

[

1

,

2

,

3

]

Mistake: A list itself is not an iterator

try

:

    next

(

numbers

)

 

TypeError: 'list' object is not an iterator

except

TypeError

as

e:

   

print

(

f

"Error: {e}"

)

Correct: Get the iterator first

iterator

=

iter

(

numbers

)

print

(

next

(

iterator

)

)

 

Output: 1

Mistake 2: Continuing to use after the iterator is exhausted

Example

numbers

=

[

1

,

2

,

3

]

iterator

=

iter

(

numbers

)

print

(

list

(

iterator

)

)

 

Output: [1, 2, 3]

print

(

list

(

iterator

)

)

 

Output: [] - The iterator is exhausted!


Practical Exercise

Exercise 1: Create a custom iterator

Create a Countdown class that implements an iterator counting down from a specified number to 1:

Example

class

Countdown:

   

def

init

(

self

,

start

)

:

       

self

.

start

=

start

   

   

def

iter

(

self

)

:

       

Your code here

        current

=

self

.

start

       

while

current

0

:

           

yield

current

            current -

=

1

Test your implementation

for

num

in

Countdown

(

5

)

:

   

print

(

num

)

 

Expected output: 5, 4, 3, 2, 1

Exercise 2: File line iterator

Create an iterator that can read a file line by line and add a line number before each line:

Example

class

NumberedLines:

   

def

init

(

self

,

filename

)

:

       

self

.

filename

=

filename

   

   

def

iter

(

self

)

:

       

with

open

(

self

.

filename

,

'r'

,

encoding

=

'utf-8'

)

as

file

:

           

for

line_num

,

line

in

enumerate

(

file

,

1

)

:

               

yield

f

"{line_num}: {line.rstrip()}"


Summary

The iterator pattern is an extremely important concept in Python programming; it allows us to:

Remember this simple principle:Any object that implements __iter__() method is iterable; any object that implements __next__() method is an iterator.