Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
Iterator Functions in Python | Set 1
Next article icon

Iterators in Python

Last Updated : 16 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

An iterator in Python is an object that holds a sequence of values and provide sequential traversal through a collection of items such as lists, tuples and dictionaries. . The Python iterators object is initialized using the iter() method. It uses the next() method for iteration.

  1. __iter__(): __iter__() method initializes and returns the iterator object itself.
  2. __next__(): the __next__() method retrieves the next available item, throwing a StopIteration exception when no more items are available.

Difference between Iterator and Iterable

Iterables are objects that can return an iterator. These include built-in data structures like lists, dictionaries, and sets. Essentially, an iterable is anything you can loop over using a for loop. An iterable implements the __iter__() method, which is expected to return an iterator object.

Iterators are the objects that actually perform the iteration. They implement two methods: __iter__() and __next__(). The __iter__() method returns the iterator object itself, making iterators iterable as well.

Python iter() Example

Python
s = "GFG" it = iter(s)  print(next(it)) print(next(it)) print(next(it)) 

Output
G F G 

Creating an iterator

Creating a custom iterator in Python involves defining a class that implements the __iter__() and __next__() methods according to the Python iterator protocol.

  • Define the Class: Start by defining a class that will act as the iterator.
  • Initialize Attributes: In the __init__() method of the class, initialize any required attributes that will be used throughout the iteration process.
  • Implement __iter__(): This method should return the iterator object itself. This is usually as simple as returning self.
  • Implement __next__(): This method should provide the next item in the sequence each time it’s called.

Below is an example of a custom class called EvenNumbers, which iterates through even numbers starting from 2:

Python
class EvenNumbers:     def __iter__(self):         self.n = 2  # Start from the first even number         return self      def __next__(self):         x = self.n         self.n += 2  # Increment by 2 to get the next even number         return x  # Create an instance of EvenNumbers even = EvenNumbers() it = iter(even)  # Print the first five even numbers print(next(it))   print(next(it))  print(next(it))   print(next(it))  print(next(it))   

Output
2 4 6 8 10 

Explanation:

  • Initialization: The __iter__() method initializes the iterator at 2, the first even number.
  • Iteration: The __next__() method retrieves the current number and then increases it by 2, ensuring the next call returns the subsequent even number.
  • Usage: We create an instance of EvenNumbers, turn it into an iterator and then use the next() function to fetch even numbers one at a time.

StopIteration Exception

The StopIteration exception is integrated with Python’s iterator protocol. It signals that the iterator has no more items to return. Once this exception is raised, further calls to next() on the same iterator will continue raising StopIteration.

Example:

Python
li = [100, 200, 300] it = iter(li)  # Iterate until StopIteration is raised while True:     try:         print(next(it))     except StopIteration:         print("End of iteration")         break 

Output
100 200 300 End of iteration 

In this example, the StopIteration exception is manually handled in the while loop, allowing for custom handling when the iterator is exhausted.


Next Article
Iterator Functions in Python | Set 1
author
kartik
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • Difference between == and is operator in Python
    In Python, == and is operators are both used for comparison but they serve different purposes. The == operator checks for equality of values which means it evaluates whether the values of two objects are the same. On the other hand, is operator checks for identity, meaning it determines whether two
    4 min read
  • Python | Set 3 (Strings, Lists, Tuples, Iterations)
    In the previous article, we read about the basics of Python. Now, we continue with some more python concepts. Strings in Python: A string is a sequence of characters that can be a combination of letters, numbers, and special characters. It can be declared in python by using single quotes, double quo
    3 min read
  • 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. [GFGTABS] Python s = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # updat
    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
    7 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 creatin
    11 min read
  • Dictionaries in Python
    A 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 t
    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
    10 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 e
    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). Additionally, Nested Loops allow looping within loops for more complex tasks. While all the ways provide similar basic functionality, they differ in th
    10 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