Python Iterators

JK 2018 
Created at
Updated at  
7,100 0 0

An iterator is an object that contains a countable number of values.

An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.

Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().


Iterator vs Iterable

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.

All these objects have a iter() method which is used to get an iterator:

mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)

print(next(myit))
print(next(myit))
print(next(myit))

Even strings are iterable objects, and can return an iterator:

mystr = "banana"
myit = iter(mystr)

print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))

Looping Through an Iterator

We can also use a for loop to iterate through an iterable object:

mytuple = ("apple", "banana", "cherry")

for x in mytuple:
  print(x)
mystr = "banana"

for x in mystr:
  print(x)

The for loop actually creates an iterator object and executes the next() method for each loop.


Create an Iterator

To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object.

As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__(), which allows you to do some initializing when the object is being created.

The __iter__() method acts similar, you can do operations (initializing etc.), but must always return the iterator object itself.

The __next__() method also allows you to do operations, and must return the next item in the sequence.

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self

  def __next__(self):
    x = self.a
    self.a += 1
    return x

myclass = MyNumbers()
myiter = iter(myclass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

StopIteration

The example above would continue forever if you had enough next() statements, or if it was used in a for loop.

To prevent the iteration from going on forever, we can use the StopIteration statement.

In the __next__() method, we can add a terminating condition to raise an error if the iteration is done a specified number of times:

class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self

  def __next__(self):
    if self.a <= 20:
      x = self.a
      self.a += 1
      return x
    else:
      raise StopIteration

myclass = MyNumbers()
myiter = iter(myclass)

for x in myiter:
  print(x)

 

Tags Iteration Python Python Iterators Facebook X
Comments 0
Similar posts
  1. Python Inheritance
    7,184
  2. Python Polymorphism
    7,079
  3. Python Scope
    7,057
  4. Python Classes/Objects
    7,454
  5. Python Modules
    7,088
  6. Python Arrays
    7,080
  7. Python Lambda
    7,096
  8. Python Functions
    7,059
  9. Python While Loops/For Loops
    7,495
  10. Python Conditions and If statements
    7,123
  11. Python Dictionaries
    7,047
  12. Python Sets
    7,083
  13. Python Tuples
    7,159
  14. Python Comparison Operators
    7,233
  15. Python Arithmetic Operators
    7,068
  16. Printing string n times
    7,061
  17. String concatenation by join()
    7,127
  18. Python Lists
    7,330
  19. Python String Operations
    7,399
  20. Python Data Types
    7,425
  21. Python Variables
    7,384
  22. Python Comments
    7,519
  23. Python Syntax
    7,397
  24. Python Getting Started
    7,447
  25. Python Introduction
    7,095
  26. What is Python?
    7,713
  27. Code Chronicles - A Caffeine-Fueled Journey into Data Software Engineering
    7,354
  28. Machine Learning Types and Programming Languages
    7,227
  29. Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship
    7,877
  30. Mastering Excel Data Manipulation with Python
    7,059
  31. Challenge: One Code Problem Per Day
    1,087
  32. Clean Python Environments: The Power of venv vs. Docker
    818
  1. Clean Python Environments: The Power of venv vs. Docker
    818
  2. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    804
  3. Mastering Excel Data Manipulation with Python
    7,059
  4. Try...Catch Helps Ignoring Data Type Miss-Match Error in Python
    9,170
  5. RegExp example in Python to exclude javascript from HTML code
    7,048
  6. Python code to convert from Lunar to Solar
    7,707
  7. Python example to download webpage
    8,574
  8. Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship
    7,877
  9. Python Modules
    7,088
  10. Python Scope
    7,057
  11. Python Polymorphism
    7,079
  12. Python Inheritance
    7,184
  13. Python Classes/Objects
    7,454
  14. Python Arrays
    7,080
  15. Python Lambda
    7,096
  16. Python Functions
    7,059
  17. Python While Loops/For Loops
    7,495
  18. Python Conditions and If statements
    7,123
  19. Python Dictionaries
    7,047
  20. Python Sets
    7,083
  21. Python Tuples
    7,159
  22. Python Comparison Operators
    7,233
  23. Python Arithmetic Operators
    7,068
  24. Printing string n times
    7,061
  25. String concatenation by join()
    7,127
  26. Python Lists
    7,330
Recently updated
  1. Watch This Dazzling Dancer’s Mind-Blowing Moves
    16
  2. Michael Jackson's Billie Jean
    98
  3. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    125
  4. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    359
  5. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    214
  6. The Evolution and Production Reality of Agentic AI
    204
  7. How to Activate or Waive Your UIUC Student Health Insurance
    287
  8. Complete Guide to Building a Machine Learning Model
    321
  9. My life cuts at Las Vegas during Thanksgiving day holiday
    7,399
  10. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    346
  11. Harness vs. OpenClaw: Two Very Different "Agents"
    968
  12. Clean Python Environments: The Power of venv vs. Docker
    818
  13. What is Docker? Why is Docker also useful in a development environment?
    613
  14. UIUC 2026-2027 Academic Calendar
    1,570
  15. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    804
  16. Open-Source LLMs: The AI Revolution
    751
  17. Resume 2.0: Leveling Up for My First Software Gig
    2,207
  18. Not everyone will understand what this man just did
    1,855
  19. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,586
  20. Unpacking IU's Shopper
    754
  21. Jackie Chan's Police Story: The Action Masterpiece
    652
  22. The IVE Story: Identity, 'I AM' Charts, and Influence
    953
  23. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,187
  24. Open Databases for Sex Crime Occurrences in the U.S.
    712
  25. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    2,632
  26. My First Day at University of Illinois-Urvana Champaign
    1,185
  27. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,126
  28. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,203
  29. Sipping the Stars: My Starbucks Adventure
    9,647
  30. Exciting explore at Sequoia National Park
    7,653
  31. My Life Shot at Death Valley
    1,701
  32. Ip Man fights with Muay Thai Master
    933
  33. Mad Clown - Don't Die
    1,013
  34. How to get Student Enrollment and Degree Verification at UIUC
    4,862
  35. LAX Thanksgiving Rush: A Joyful Reunion
    920
  36. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,125
  37. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    971
  38. 10CM - To Reach You (너에게 닿기를)
    1,152
  39. Feeling weak? Transform yourself at the UIUC ARC!
    1,571
  40. BOYNEXTDOOR - If I Say I Love You
    1,181
  41. The Future of Software Engineer - AI Engineering
    927
  42. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    900
  43. Lie - Legend song by BIGBANG
    7,812
  44. Why ROLLBACK is useful when you work with Google Gemini CLI?
    832
  45. Reimbursement after Vaccination at McKinley Health Center
    1,016
  46. Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!
    966
  47. Common Questions from UIUC school life in terms of CS Program
    1,117
  48. UIUC Immunization Compliance
    1,211
  49. LEE CHANHYUK's songs really resonate with my soul - Time Stop! Vivid LaLa Love, Eve, Endangered Love ...
    1,091
  50. LEE CHANHYUK - Endangered Love (멸종위기사랑)
    1,092