Tutorial Gateway

  • C
  • C#
  • Python
  • SQL
  • Java
  • JS
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Go Programs
    • Python Programs
    • Java Programs
  • MySQL

Python Iterator

An Iterator in Python is an Object which contains a countable number of values or elements. You can use this Python iterator to Traverse all those elements. The Python iterator uses the special methods called __iter__() and __next__() methods to iterate the object elements.

Python Iterables vs Iterator

 If we can get an iterator from it, then we call that object as iterable. So far, we have seen the iterables called Lists, Tuples, Sets, and Dictionaries. From these objects, you can call iterator or Iter. This section explains how to use the Iterator in Python and create our own iterators and infinity iterators with practical examples.

Python String Iterator Example

In python, strings are iterable objects. Here, we use for loop to iterate each character in a string and returns that character. By default, or say, For loop implements the Iterator concept without your knowledge.

# Python Iterator Example
 
string = 'tutorialgateway'
 
for x in string:
    print(x, end = '  ')
Python Iterator 1

Python Iterators For loop Example 2

In this example, we used both for loop and iterators. In python, we have to use the next() function to return an element or value from an iterator. Remember, the Python next() function returns one item at a time. So, for n number of items, you have to use n next() statements. Here, we used the next() for one time. So, it returns the first character from a string.

string = 'tutorialgateway'
  
for x in string:
     print(x, end = '  ')
  
print("\n**** Iterator Example *****")
itr = iter(string)
  
print(next(itr))
Python Iterator 2

Let me use next() to iterate all the characters in a string. This time, the Python writes the completed string.

string = 'tutorialgateway'
 
for x in string:
    print(x, end = '  ')
 
print("\n**** Iterator Example *****")
itr = iter(string)
 
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
Python Iterator 3

Python List Iterator

In this example, we show how to iterate List items and prints them.

numbers = [10, 20, 30, 40, 50]
 
itr = iter(numbers)
 
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
print(next(itr))
Python Iterator 4

In this list iterator example, we used the __next__() special method. If you observe the last statement, we are trying to return the next element that doesn’t exist. That’s why Python Iterator is calling StopIteration.

numbers = [10, 20, 30, 40, 50]
 
itr = iter(numbers)
 
print(itr.__next__())
print(itr.__next__())
print(itr.__next__())
print(itr.__next__())
print(itr.__next__())
print(itr.__next__())
Python Iterator 5

Python Set Iterator

You can use the Iterator to iterate the set items too. This program iterates the numbers in a Set and prints each one of them.

mySet = {1, 2, 3, 4, 5}
 
ittr = iter(mySet)
 
print(ittr.__next__())
print(ittr.__next__())
print(ittr.__next__())
print(ittr.__next__())
print(ittr.__next__())
Python Iterator 6

Tuple Iterator

Python also allows you to use this on Tuples as well. This program iterates Tuple items and prints each item in a tuple.

fruits = ('Apple', 'Orange', 'Grape', 'Banana', 'Kiwi')
 
fruit_itr = iter(fruits)
 
print(next(fruit_itr))
print(next(fruit_itr))
print(next(fruit_itr))
print(next(fruit_itr))
print(next(fruit_itr))
Python tuple Iterator 7

Create Own Iterator in Python

It is a simple class called Counter. First, we declared a maximum value within the __init__ method. The __iter__ method is to initialize the value of an iterable object. For now, we set the number to 0. It means Iterator starts at 0.

The __next__ method is to select the next element from an Object. Within this method, we used the If Else Statement to check whether the next number is greater than the maximum value or not. If True, StopIteration error raised. Otherwise, the number incremented.

class Counter:
 
    def __init__(self, maximum):
        self.maximum = maximum

    def __iter__(self):
        self.number = 0
        return self
 
    def __next__(self):
        number = self.number
 
        if number > self.maximum:
            raise StopIteration
        else:
            self.number = number + 1
            return number
 
numbers = Counter(10)
a = iter(numbers)

print(next(a))
print(next(a))
print(next(a))
Python Iterator 8

Python Own Iterator Example 2

The above iterator code is displaying numbers from 0 to 2. It is because we used next(a) for three times only. In this program, we used for loop to iterate the Counter class where the maximum value is 10. This prints the values from 0 to 10. __iter__() starts at 0, and __next__() print elements up to 10.

class Counter:
 
    def __init__(self, maximum):
        self.maximum = maximum
 
    def __iter__(self):
        self.number = 0
        return self
 
    def __next__(self):
        number = self.number
 
        if number > self.maximum:
            raise StopIteration
        else:
            self.number = number + 1
            return number
 
for t in Counter(10):
    print(t)
Python Iterator 9

Python Infinity Iterator

While you create your own iterator, you should always be careful with Infinity loops. If you forget to raise the StopIterator error, then you end up in infinity loops. It is a simple example of an infinity iterator. It is the same as above, but we removed the If statement.

class Counter:
 
    def __iter__(self):
        self.number = 0
        return self

    def __next__(self):
        number = self.number

        self.number = number + 1
        return number
      
numbers = Counter()
a = iter(numbers)
 
print(next(a))
print(next(a))
print(next(a))
Python Infinite Iterator 10

Although the above example is an infinite iterator, you might not have noticed it. It is because we used the next() for three times only. So, let me use for loop to an iterator the Counter class.

class Counter:
 
    def __iter__(self):
        self.number = 0
        return self
 
    def __next__(self):
        number = self.number
 
        self.number = number + 1
        return number
     
for t in Counter():
    print(t)

Now you can see the Python infinity iterator. This iterator executes continuously. Please refer to Python Dictionary article.

Python Iterator 11

Filed Under: Python

  • Download and Install Python
  • Python Arithmetic Operators
  • Python Assignment Operators
  • Python Bitwise Operators
  • Python Comparison Operators
  • Python Logical Operators
  • Python If Statement
  • Python If Else
  • Python Elif Statement
  • Python Nested If
  • Python For Loop
  • Python While Loop
  • Python Break
  • Python Continue
  • Python Dictionary
  • Python datetime
  • Python String
  • Python Set
  • Python Tuple
  • Python List
  • Python List Comprehensions
  • Python Lambda Function
  • Python Functions
  • Python Types of Functions
  • Python Iterator
  • Python File Handling
  • Python Directory
  • Python Class
  • Python classmethod
  • Python Inheritance
  • Python Method Overriding
  • Python Static Method
  • Connect Python and SQL Server
  • Python SQL Create DB
  • Python SQL Select Top
  • Python SQL Where Clause
  • Python SQL Order By
  • Python SQL Select Statement
  • Python len Function
  • Python max Function
  • Python map Function
  • Python print Function
  • Python sort Function
  • Python range Function
  • Python zip Function
  • Python Math Functions
  • Python String Functions
  • Python List Functions
  • Python NumPy Array
  • NumPy Aggregate Functions
  • NumPy Arithmetic Operations
  • Python Numpy Bitwise operators
  • Numpy Comparison Operators
  • Numpy Exponential Functions
  • Python Numpy logical operators
  • Python numpy String Functions
  • NumPy Trigonometric Functions
  • Python random Array
  • Python numpy concatenate
  • Python numpy Array shape
  • Python pandas DataFrame
  • Pandas DataFrame plot
  • Python Series
  • Python matplotlib Histogram
  • Python matplotlib Scatter Plot
  • Python matplotlib Pie Chart
  • Python matplotlib Bar Chart
  • Python List Length
  • Python sort List Function
  • Python String Concatenation
  • Python String Length
  • Python substring
  • Python Programming Examples

Copyright © 2021ยท All Rights Reserved by Suresh.
About | Contact | Privacy Policy