Close Menu
TechBeamersTechBeamers
    TechBeamersTechBeamers
    • Python
    • Java
    • C
    • SQL
    • MySQL
    • Selenium
    • Testing
    • Agile
    • Linux
    • WebDev
    • Technology
    TechBeamersTechBeamers
    Python Advanced

    Iterators in Python

    By Meenakshi AgarwalUpdated:Nov 23, 2023No Comments4 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    From this tutorial, you will be learning about Python Iterator. It is a type of container holding references to other elements. It provides the next() method to access each item.  Today, you’ll see how it works and also get to use built-in iterators like lists, tuples, etc. with examples.

    Moreover, Python permits us to create user-defined iterators. We can do so by defining it using a Python class. The class then has to implement the required iterator properties and methods. We’ve got it covered in this tutorial and also provided code for practice.

    Note: The syntax used here is for Python 3. You may modify it to use with other versions of Python.

    What is Python Iterator?

    An iterator is a collection object that holds multiple values and provides a mechanism to traverse through them. Examples of inbuilt iterators in Python are lists, dictionaries, tuples, etc.

    It works according to the iterator protocol. The protocol requires to implement two methods. They are __iter__ and __next__.

    The __iter__() function returns an iterable object, whereas the __next__() gives a reference of the following items in the collection.

    How to use iterators in Python?

    Most of the time, you have to use an import statement for calling functions of a module in Python. However, iterators don’t need one as you can use them implicitly.

    When you create an object, you can make it iterable by calling the __iter__() method over it. After that, you can iterate its values with the help of __next__(). When there is nothing left to traverse, then you get the StopIteration exception. It indicates that you’ve reached the end of the iterable object.

    See also  Python For Loop Tutorial

    The for loop automatically creates an iterator while traversing through an object’s element.

    The following flowchart attempts to simplify the concept for you.

    Python Iterators Flowchart

    Iterator Syntax

    To use iterators, you can use the methods as defined above __iter__ and __next__ methods.

    You can create an iterable object as per the below instruction:

    iterable_object = iter(my_object_to_iterate_through)

    Once, you get a hold of the iterator, then use the following statement to cycle through it.

    iterable_object = iter(my_object_to_iterate_through)
    next(iterable_object)

    By the way, the Python zip function can be quite useful in your regular programming tasks. It helps you iterate, combine, compare, and search over multiple lists.

    Iterator Examples

    For illustration, here are some Python code examples where you can learn how to use the iterator.

    Creating an iterable from Tuple

    Cubes = (1, 8, 27, 64, 125, 216)
    cube = iter(Cubes)
    print(next(cube))
    print(next(cube))

    Output

    1
    8

    Creating an iterable from List

    Negative_numbers = [-1, -8, -27, -64, -125, -216]
    Negative_number = iter(Negative_numbers)
    print(next(Negative_number))
    print(next(Negative_number))

    Output

    -1
    -8

    Iterating through an empty object

    List = []
    empty_element = iter(List)
    print(next(empty_element))
    print(next(empty_element))

    Output

    Traceback (most recent call last):
    File "C:\Users\porting-dev\AppData\Local\Programs\Python\Python35\test11.py", line 3, in <module>
    next(empty_element)
    StopIteration

    Iterating a non-existent object

    List = [1,2,3,4]
    empty = iter(List)
    print(next(empty))
    print(next(empty))
    
    # Output
    # 1 2

    Printing a list of natural numbers

    The below example provides a script that can get called or executed in the interpreter shell.

    Please be careful about the indentation blocks when you enter the code in the interpreter shell.

    class natural_numbers:
        def __init__(self, max = 0):
            self.max = max
        def __iter__(self):
            self.number = 1
            return self
    
        def __next__(self):
            if self.max == self.number:
                raise StopIteration
            else:
                number = self.number
                self.number += 1
                return number
    
    numbers = natural_numbers(10)
    i = iter(numbers)
    print("# Calling next() one by one:")
    print(next(i))
    print(next(i))
    print("\n")
    
    # Call next method in a loop
    print("# Calling next() in a loop:")
    for i in numbers:
        print(i)

    To execute the above program, use the command python3 /path_to_filename depending upon the default Python version used. The following is the output of the above Python iterator program.

    # Calling next() one by one:
    1 2
    
    # Calling next() in a loop:
    1 2 3 4 5 6 7 8 9

    Summary – Iterator in Python

    We hope that after wrapping up this tutorial, you must be feeling comfortable using the Python iterator. However, you may practice more with examples to gain confidence.

    See also  Convert a List to String in Python

    Next, we recommend you read about generators in Python. They are also used to create iterators but in a much easier fashion. You don’t need to write __iter__() and __next__() functions. Instead, you write a generator function that uses the yield statement for returning a value.

    The yield’s call saves the state of the function and resumes from the same point if called again. It helps the code to generate a set of values over time, rather than getting them all at once. You can get the complete details from the below tutorial.

    Python Generator

    Previous ArticleList Copy in Python
    Next Article List Index Method in Python
    Meenakshi Agarwal

    I'm Meenakshi Agarwal, founder of TechBeamers.com, with 10+ years of experience in Software development, testing, and automation. Proficient in Python, Java, Selenium, SQL, & C-Sharp, I create tutorials, quizzes, exercises and interview questions on diverse tech topics. Follow my tutorials for valuable insights!

    Add A Comment

    Leave A Reply Cancel Reply

    Python Coding Exercises for Beginners
    • 40 Python Exercises for Beginners
    • 6 Python Data Class Exercises
    • 100+ Python Interview Questions for 2024
    • 20 Python Programs to Print Patterns
    Python Basic Tutorials
    • Python Keyword
    • Python Statement
    • Python Comment
    • Python Data Types
    • Python String Methods
    • Python Multiline Strings
    • Python Split Strings
    • Python Slice Strings
    • Iterate Strings in Python
    • Python String Format
    • Python String Concatenation
    • Python Permutations of a String
    • Python Numbers
    • Python List
    • Python List Reverse
    • Python List Slice
    • Python Nested List
    • Python Set
    • Python Tuple
    • Python Dictionary
    • Python Dict to JSON
    • Python Dictionary Examples
    • Python OrderedDict
    • Python Arrays
    • Python Generate SubArrays
    • Python Heapq (Heap queue)
    • Python Operators
    • Python XOR Operator
    • Operator Precedence
    • Python Namespace
    • Python For Loop
    • Python While Loop
    • Python If Else
    • Python Switch Case
    • Python Function
    • Higher Order Functions in Python
    • Python Class
    • Python Class Definition
    • Python Data Class
    • Python Inheritance
    • Python Multiple Inheritance
    • Python Static Method
    • File Handling in Python
    • Python Copy File
    • Python Exception Handling
    • Python Try Except
    • Python Lambda
    • Python Generator
    • Python Module
    Python Pandas in Action
    • Rename Columns using Pandas
    • Python Pandas to Read CSV Files
    • Python Pandas to Merge CSV Files
    • Python Dictionary to DataFrame
    • Python Find Length of List
    Python Important Functions
    • Python Glob()
    • Python Range()
    • Python Float Range()
    • Python Map()
    • Python Filter()
    • Python Enumerate()
    • Python Zip()
    • Python Join()
    • Python Ord()
    Python Advanced Tutorials
    • Python Multithreading
    • Python Socket Programming
    • Selenium Python
    • Python Unittest
    • Python Time Module
    • Python Datetime
    • Python IRC
    • PyLint in Python
    • Python Random Number
    • Python MongoDB
    • Python Pickle
    Python Code Examples
    • Python List Contains Elements
    • Python Search Dictionary by Value
    • Python Check Type of Variable
    • Python Check Version Using Code
    • Python Loop Through Files
    • Compare Strings in Python
    • Replace Strings in Python
    • Size of Integer in Python
    • Simple Socket in Python
    • Threaded Socket in Python
    Python Tips & Tricks
    • 30 Essential Python Tips
    • 10 Python Coding Tips
    • 12 Python Code Optimization Tips
    • 10 Python Programming Mistakes
    Python General Topics
    • Top 10 Python IDEs
    • Top 7 Python Interpreters
    • Top 7 Websites for Python
    • Top 5 Chrome Plugin for Python
    Python Quizzes - General
    • Python Quiz-1
    • Python Quiz-2
    • Python Quiz-3
    • Python Quiz-4
    Python Quizzes - Advanced
    • Python Quiz - Data Structures
    • Python Quiz - Threads
    • Python Quiz - DA
    Python MCQ - Strings
    • Python MCQ Strings-1
    • Python MCQ Strings-2
    Python MCQ - Classes `
    • Python MCQ Classes-1
    • Python MCQ Classes-2
    Python MCQ - Functions
    • Python MCQ Functions-1
    • Python MCQ Functions-2
    Python MCQ - File I/O
    • Python MCQ File I/O-1
    • Python MCQ File I/O-2
    Latest Posts
    • 30 Python Programming Questions On List, Tuple, and Dictionary
    • 4 Different Ways to Rename Columns in Pandas
    • 4 Unique Ways to Reverse a String in Python
    • 40 Google Interview Questions You Need to Join Google in 2023
    • 40 Python Exercises for Beginners
    • 44 Python Data Analyst Interview Questions
    • 7 Websites to Learn Python Programming

    Subscribe to Updates

    Get the latest tutorials from TechBeamers.

    Loading
    • About
    • Contact
    • Disclaimer
    • Privacy Policy
    • Terms of Use
    © 2023 TechBeamers. All Rights Reserved.

    Type above and press Enter to search. Press Esc to cancel.