Python Iterators

JK JK 2038 
Created at
Updated at  
7,176 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,270
  2. Python Polymorphism
    7,156
  3. Python Scope
    7,134
  4. Python Classes/Objects
    7,579
  5. Python Modules
    7,178
  6. Python Arrays
    7,165
  7. Python Lambda
    7,173
  8. Python Functions
    7,124
  9. Python While Loops/For Loops
    7,617
  10. Python Conditions and If statements
    7,186
  11. Python Dictionaries
    7,162
  12. Python Sets
    7,165
  13. Python Tuples
    7,264
  14. Python Comparison Operators
    7,343
  15. Python Arithmetic Operators
    7,140
  16. Printing string n times
    7,119
  17. String concatenation by join()
    7,183
  18. Python Lists
    7,457
  19. Python String Operations
    7,538
  20. Python Data Types
    7,550
  21. Python Variables
    7,516
  22. Python Comments
    7,671
  23. Python Syntax
    7,499
  24. Python Getting Started
    7,570
  25. Python Introduction
    7,164
  26. What is Python?
    7,824
  27. Code Chronicles - A Caffeine-Fueled Journey into Data Software Engineering
    7,461
  28. Machine Learning Types and Programming Languages
    7,328
  29. Python Tutorials for AP Computer Science Principles, Data Projects and High School Internship
    8,052
  30. Mastering Excel Data Manipulation with Python
    7,146
  31. Challenge: One Code Problem Per Day
    1,259
  32. Clean Python Environments: The Power of venv vs. Docker
    1,068
  1. How to Build Llama 3 AI Apps with Python: Setup & User Prompts
    1,034
  2. Try...Catch Helps Ignoring Data Type Miss-Match Error in Python
    9,548
  3. RegExp example in Python to exclude javascript from HTML code
    7,117
  4. Python code to convert from Lunar to Solar
    7,894
  5. Python example to download webpage
    8,868
Recently updated
  1. Comprehensive Guide to Recent Critical PHP Vulnerabilities
    713
  2. How to Check Your UIUC Graduation Progress Using DARS Audit
    632
  3. Michael Jackson's Billie Jean
    359
  4. Meet A2O Lite: Korea's Newest K-Pop Cuties with Addictively Catchy Melodies
    290
  5. Why You Can't Stop Watching Jack Bryan's Beatbox Gaming Shorts
    298
  6. Song So-hee: The Soulful Voice Touching Hearts Through Korean Music
    314
  7. Watch This Dazzling Dancer’s Mind-Blowing Moves
    332
  8. Bootstrap vs. Tailwind CSS: Origins, Features, Pros & Cons, and How to Choose the Right Framework
    356
  9. The Complete Guide to Golang: History, Features, Real-World Uses, and Code Examples
    1,146
  10. Telemetry vs. Analytics: Understanding the Difference and Why It Matters
    511
  11. The Evolution and Production Reality of Agentic AI
    394
  12. How to Activate or Waive Your UIUC Student Health Insurance
    502
  13. Complete Guide to Building a Machine Learning Model
    517
  14. My life cuts at Las Vegas during Thanksgiving day holiday
    7,583
  15. The Cybercab Transformation: From Autonomous Taxi to Mobile Base Station
    539
  16. Harness vs. OpenClaw: Two Very Different "Agents"
    1,305
  17. What is Docker? Why is Docker also useful in a development environment?
    784
  18. UIUC 2026-2027 Academic Calendar
    1,935
  19. Open-Source LLMs: The AI Revolution
    952
  20. Resume 2.0: Leveling Up for My First Software Gig
    2,855
  21. Not everyone will understand what this man just did
    2,350
  22. UIUC Dorm Guide: Find Your Perfect Fit !!
    1,811
  23. Unpacking IU's Shopper
    952
  24. Jackie Chan's Police Story: The Action Masterpiece
    830
  25. The IVE Story: Identity, 'I AM' Charts, and Influence
    1,156
  26. Tech Visionaries who graduated at UIUC - You are the Next Turn
    1,358
  27. Open Databases for Sex Crime Occurrences in the U.S.
    933
  28. Automatically copy text to the clipboard when dragging the mouse in the Cursor
    3,276
  29. My First Day at University of Illinois-Urvana Champaign
    1,353
  30. Sand, Sea, and a Splash of Fun at Newport Beach: A Family Adventure
    8,379
  31. Sun, Rocks, and Adventure: A Day at Joshua Tree National Park
    8,450
  32. Sipping the Stars: My Starbucks Adventure
    10,062
  33. Exciting explore at Sequoia National Park
    7,840
  34. My Life Shot at Death Valley
    2,001
  35. Ip Man fights with Muay Thai Master
    1,107
  36. Mad Clown - Don't Die
    1,224
  37. How to get Student Enrollment and Degree Verification at UIUC
    5,689
  38. LAX Thanksgiving Rush: A Joyful Reunion
    1,063
  39. ZO ZAZZ(조째즈) - Don`t you know (모르시나요) (PROD.ROCOBERRY)
    1,321
  40. FISHINGIRLS Unleashes Energetic EP 'Funiverse' Featuring Signature Track 'Fishing King'
    1,129
  41. 10CM - To Reach You (너에게 닿기를)
    1,313
  42. Feeling weak? Transform yourself at the UIUC ARC!
    1,718
  43. BOYNEXTDOOR - If I Say I Love You
    1,346
  44. The Future of Software Engineer - AI Engineering
    1,073
  45. G Dragon x Taeyang (Eyes Nose Lips, Power, Home Sweet Home, GOOD BOY) - LE GALA PIÈCES JAUNES 2025
    1,080
  46. Lie - Legend song by BIGBANG
    7,976
  47. Why ROLLBACK is useful when you work with Google Gemini CLI?
    1,077
  48. Reimbursement after Vaccination at McKinley Health Center
    1,184
  49. Gemini CLI makes a Magic! Time to speed up your app development with Google Gemini CLI!
    1,126
  50. Common Questions from UIUC school life in terms of CS Program
    1,310