TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Iterators in Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python AdvancedPython Tutorials

Iterators in Python

Last updated: Nov 23, 2023 11:24 am
By Meenakshi Agarwal
Share
6 Min Read
Python Iterator Tutorial for Beginners
Python Iterator Tutorial for Beginners
SHARE

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.

Contents
Iterator SyntaxCreating an iterable from TupleCreating an iterable from ListIterating through an empty objectIterating a non-existent objectPrinting a list of natural numbers

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.

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.

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

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python List Copy Method with Examples List Copy in Python
Next Article Python List Index Method Explained with Examples List Index Method in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x
x