Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Converting an object into an iterator
Next article icon

Converting an object into an iterator

Last Updated : 10 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, we often need to make objects iterable, allowing them to be looped over like lists or other collections. Instead of using complex generator loops, Python provides the __iter__() and __next__() methods to simplify this process.

Iterator Protocol:

  • __iter__(): Returns the iterator object itself.
  • __next__(): Returns the next item in the sequence or raises StopIteration when there are no more items.

Example: Creating an Iterable Object

Python
a = ['a', 'e', 'i', 'o', 'u']  iter_a = iter(a)  print(next(iter_a)) print(next(iter_a)) print(next(iter_a)) print(next(iter_a)) print(next(iter_a)) 

Output
a e i o u 

Explanation: List a is converted into an iterator iter_a and next() retrieves each element sequentially. Once exhausted, further calls to next(iter_a) raise a StopIteration exception.

Python __iter__()

The __iter__() function in Python returns an iterator for the given object (e.g., array, set, tuple, or a custom object). It creates an object that can be accessed one element at a time using __next__(). This is particularly useful when dealing with loops.

Syntax:

iter(object)

iter(callable, sentinel)

object: The object whose iterator is created. It can be a collection like a list or a user-defined object.

callable, sentinel:

  • callable: A function that generates values dynamically.
  • sentinel: The value at which iteration stops.

Example: Using iter(callable,sentinel)

Python
import random rand_iter = iter(lambda: random.randint(1, 10), 5)  # Stops when 5 is generated  for num in rand_iter:     print(num) 

Output
8 7 1 1 7 9 

Explanation: This code creates an iterator that generates random numbers from 1 to 10, stopping when 5 appears. The for loop prints numbers until 5 is encountered, making the output vary each run.

Python __next__()

The __next__() function in Python returns the next element of an iteration. If there are no more elements, it raises the StopIteration exception. It is part of the iterable and iterator interface, which allows us to create custom iterable objects, such as generators, and control how elements are retrieved one at a time.

Example 1. Using __next__() in loop

Python
a = [11, 22, 33, 44, 55]  iter_a = iter(a) while True:     try:         print(iter_a.__next__())     except StopIteration:         break 

Output
11 22 33 44 55 

Explanation: List a is converted into an iterator iter_a and a while True loop is used to retrieve elements using __next__(). A try-except block handles StopIteration, ensuring iteration stops gracefully when the iterator is exhausted.

Example 2. Exception handling

Python
a = ['Cat', 'Bat', 'Sat', 'Mat']  iter_a = iter(a)  try:     print(iter_a.__next__())     print(iter_a.__next__())     print(iter_a.__next__())     print(iter_a.__next__())     print(iter_a.__next__())  # Raises StopIteration error except StopIteration:     print("\nThrowing 'StopIterationError': Cannot iterate further.") 

Output
Cat Bat Sat Mat  Throwing 'StopIterationError': Cannot iterate further. 

Explanation: List a is converted into an iterator iter_a and__next__() retrieves elements sequentially. When exhausted, StopIteration is caught, displaying a custom message.

Using __iter__() and __next__() in user-defined objects

We can implement the iterator protocol in user-defined classes by defining __iter__() and __next__() methods. The __iter__() method should return the iterator object and __next__() should return the next element in the sequence.

Example:

Python
class Counter:     def __init__(self, start, end):         self.num = start         self.end = end      def __iter__(self):         return self      def __next__(self):         if self.num > self.end:             raise StopIteration         else:             self.num += 1             return self.num - 1  # Driver code if __name__ == '__main__':     a, b = 2, 5     c1 = Counter(a, b)     c2 = Counter(a, b)          # Iteration without using iter()     print("Print the range without iter():")     for i in c1:         print("Counting:", i)          print("\nPrint the range using iter():")          # Using iter()     obj = iter(c2)     try:         while True:  # Iterate until StopIteration is raised             print("Counting:", next(obj))     except StopIteration:         print("\nIteration completed.") 

Output
Print the range without iter(): Counting: 2 Counting: 3 Counting: 4 Counting: 5  Print the range using iter(): Counting: 2 Counting: 3 Counting: 4 Counting: 5  Iteration completed. 

Explanation: The Counter class iterates from start to end, with __iter__() returning itself and __next__() incrementing until StopIteration. The first loop iterates over c1, while the second uses iter(c2) and next(obj), handling exhaustion gracefully.


Next Article
Converting an object into an iterator
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Python
  • Python-Functions
  • Python-Built-in-functions
Practice Tags :
  • python
  • python-functions

Similar Reads

    Python String
    A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut
    6 min read
    Python Lists
    In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
    6 min read
    Python Tuples
    A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
    6 min read
    Python Sets
    Python set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can change.Creating a Set in PythonIn Python, the most basic and efficient method for creating
    10 min read
    Dictionaries in Python
    Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
    5 min read
    Python Arrays
    Lists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences:Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
    9 min read
    Python If Else Statements - Conditional Statements
    In Python, If-Else is a fundamental conditional statement used for decision-making in programming. If...Else statement allows to execution of specific blocks of code depending on the condition is True or False.if Statementif statement is the most simple decision-making statement. If the condition ev
    4 min read
    Loops in Python - For, While and Nested Loops
    Loops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). In this article, we will look at Python loops and understand their working with the help of examples. While Loop in PythonIn Python, a while loop is us
    9 min read
    Loops and Control Statements (continue, break and pass) in Python
    Python supports two types of loops: for loops and while loops. Alongside these loops, Python provides control statements like continue, break, and pass to manage the flow of the loops efficiently. This article will explore these concepts in detail.Table of Contentfor Loopswhile LoopsControl Statemen
    2 min read
    range() vs xrange() in Python
    The range() and xrange() are two functions that could be used to iterate a certain number of times in for loops in Python. In Python3, there is no xrange, but the range function behaves like xrange in Python2. If you want to write code that will run on both Python2 and Python3, you should use range(
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences