Python Iterators

JK JK 2030 
Created at
Updated at  
7,133 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,221
  2. Python Polymorphism
    7,106
  3. Python Scope
    7,085
  4. Python Classes/Objects
    7,511
  5. Python Modules
    7,135
  6. Python Arrays
    7,113
  7. Python Lambda
    7,131
  8. Python Functions
    7,088
  9. Python While Loops/For Loops
    7,552
  10. Python Conditions and If statements
    7,156
  11. Python Dictionaries
    7,087
  12. Python Sets
    7,134
  13. Python Tuples
    7,200
  14. Python Comparison Operators
    7,292
  15. Python Arithmetic Operators
    7,107
  16. Printing string n times
    7,093
  17. String concatenation by join()
    7,158
  18. Python Lists
    7,391
  19. Python String Operations
    7,475
  20. Python Data Types
    7,485
  21. Python Variables
    7,457
  22. Python Comments
    7,611
  23. Python Syntax
    7,445
  24. Python Getting Started
    7,509
  25. Python Introduction
    7,128
  26. What is Python?
    7,775
  27. Code Chronicles - A Caffeine-Fueled Journey into Data Software Engineering
    7,413
  28. Machine Learning Types and Programming Languages
    7,284
  29. Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship
    7,979
  30. Mastering Excel Data Manipulation with Python
    7,108
  31. Challenge: One Code Problem Per Day
    1,187
  32. Clean Python Environments: The Power of venv vs. Docker
    959
  1. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    921
  2. Try...Catch Helps Ignoring Data Type Miss-Match Error in Python
    9,334
  3. RegExp example in Python to exclude javascript from HTML code
    7,081
  4. Python code to convert from Lunar to Solar
    7,796
  5. Python example to download webpage
    8,705
Recently updated
  1. Michael Jackson's Billie Jean
    278
  2. Meet A2O Lite: Korea's Newest K-Pop Cuties with Addictively Catchy Melodies
    91
  3. Why You Can't Stop Watching Jack Bryan's Beatbox Gaming Shorts
    169
  4. Song So-hee: The Soulful Voice Touching Hearts Through Korean Music
    188
  5. Watch This Dazzling Dancer’s Mind-Blowing Moves
    207
  6. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    252
  7. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    769
  8. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    383
  9. The Evolution and Production Reality of Agentic AI
    315
  10. How to Activate or Waive Your UIUC Student Health Insurance
    404
  11. Complete Guide to Building a Machine Learning Model
    430
  12. My life cuts at Las Vegas during Thanksgiving day holiday
    7,517
  13. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    456
  14. Harness vs. OpenClaw: Two Very Different "Agents"
    1,139
  15. What is Docker? Why is Docker also useful in a development environment?
    707
  16. UIUC 2026-2027 Academic Calendar
    1,785
  17. Open-Source LLMs: The AI Revolution
    872
  18. Resume 2.0: Leveling Up for My First Software Gig
    2,532
  19. Not everyone will understand what this man just did
    2,109
  20. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,708
  21. Unpacking IU's Shopper
    878
  22. Jackie Chan's Police Story: The Action Masterpiece
    751
  23. The IVE Story: Identity, 'I AM' Charts, and Influence
    1,058
  24. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,282
  25. Open Databases for Sex Crime Occurrences in the U.S.
    825
  26. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    2,949
  27. My First Day at University of Illinois-Urvana Champaign
    1,283
  28. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,275
  29. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,354
  30. Sipping the Stars: My Starbucks Adventure
    9,851
  31. Exciting explore at Sequoia National Park
    7,774
  32. My Life Shot at Death Valley
    1,859
  33. Ip Man fights with Muay Thai Master
    1,038
  34. Mad Clown - Don't Die
    1,137
  35. How to get Student Enrollment and Degree Verification at UIUC
    5,252
  36. LAX Thanksgiving Rush: A Joyful Reunion
    999
  37. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,233
  38. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    1,070
  39. 10CM - To Reach You (너에게 닿기를)
    1,245
  40. Feeling weak? Transform yourself at the UIUC ARC!
    1,658
  41. BOYNEXTDOOR - If I Say I Love You
    1,269
  42. The Future of Software Engineer - AI Engineering
    1,009
  43. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    1,002
  44. Lie - Legend song by BIGBANG
    7,909
  45. Why ROLLBACK is useful when you work with Google Gemini CLI?
    950
  46. Reimbursement after Vaccination at McKinley Health Center
    1,109
  47. Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!
    1,048
  48. Common Questions from UIUC school life in terms of CS Program
    1,225
  49. UIUC Immunization Compliance
    1,305
  50. LEE CHANHYUK's songs really resonate with my soul - Time Stop! Vivid LaLa Love, Eve, Endangered Love ...
    1,176