Open In App

Iterators in Python

Last Updated : 26 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

An iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets. The Python iterators object is initialized using the iter() method. It uses the next() method for iteration.

  1. __iter__(): The iter() method is called for the initialization of an iterator. This returns an iterator object
  2. __next__(): The next method returns the next value for the iterable. When we use a for loop to traverse any iterable object, internally it uses the iter() method to get an iterator object, which further uses the next() method to iterate over. This method raises a StopIteration to signal the end of the iteration.

Python iter() Example

Python3




string = "GFG"
ch_iterator = iter(string)
 
print(next(ch_iterator))
print(next(ch_iterator))
print(next(ch_iterator))


Output : 

G
F
G

Creating and looping over an iterator using iter() and next()

Below is a simple Python Iterator that creates an iterator type that iterates from 10 to a given limit. For example, if the limit is 15, then it prints 10 11 12 13 14 15. And if the limit is 5, then it prints nothing.

Python3




# A simple Python program to demonstrate
# working of iterators using an example type
# that iterates from 10 to given value
 
# An iterable user defined type
class Test:
 
    # Constructor
    def __init__(self, limit):
        self.limit = limit
 
    # Creates iterator object
    # Called when iteration is initialized
    def __iter__(self):
        self.x = 10
        return self
 
    # To move to next element. In Python 3,
    # we should replace next with __next__
    def __next__(self):
 
        # Store current value ofx
        x = self.x
 
        # Stop iteration if limit is reached
        if x > self.limit:
            raise StopIteration
 
        # Else increment and return old value
        self.x = x + 1;
        return x
 
# Prints numbers from 10 to 15
for i in Test(15):
    print(i)
 
# Prints nothing
for i in Test(5):
    print(i)


Output:

10
11
12
13
14
15

Iterating over built-in iterable using iter() method

In the following iterations, the iteration state and iterator variable is managed internally (we can’t see it) using an iterator object to traverse over the built-in iterable like list, tuple, dict, etc.

Python3




# Sample built-in iterators
 
# Iterating over a list
print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
    print(i)
     
# Iterating over a tuple (immutable)
print("\nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
    print(i)
     
# Iterating over a String
print("\nString Iteration")   
s = "Geeks"
for i in s :
    print(i)
     
# Iterating over dictionary
print("\nDictionary Iteration")  
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
    print("%s  %d" %(i, d[i]))


Output:

List Iteration
geeks
for
geeks

Tuple Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

Dictionary Iteration
xyz  123
abc  345

Iterable vs Iterator

Python iterable and Python iterator are different. The main difference between them is, iterable in Python cannot save the state of the iteration, whereas in iterators the state of the current iteration gets saved.

Note: Every iterator is also an iterable, but not every iterable is an iterator in Python
Read moreDifference between iterable and iterator.

Iterating on an Iterable

Iterating on each item of the iterable.

Python3




tup = ('a', 'b', 'c', 'd', 'e')
 
for item in tup:
    print(item)


Output:

a
b
c
d
e

Iterating on an iterator

Python3




tup = ('a', 'b', 'c', 'd', 'e')
 
# creating an iterator from the tuple
tup_iter = iter(tup)
 
print("Inside loop:")
# iterating on each item of the iterator object
for index, item in enumerate(tup_iter):
    print(item)
 
    # break outside loop after iterating on 3 elements
    if index == 2:
        break
 
# we can print the remaining items to be iterated using next()
# thus, the state was saved
print("Outside loop:")
print(next(tup_iter))
print(next(tup_iter))


Output:

Inside loop:
a
b
c
Outside loop:
d
e

Getting StopIteration Error while using iterator

Iterable in Python can be iterated over multiple times, but iterators raise StopIteration Error when all items are already iterated.

Here, we are trying to get the next element from the iterator after the completion of the for-loop. Since the iterator is already exhausted, it raises a StopIteration Exception. Whereas, using an iterable, we can iterate on multiple times using for loop or can get items using indexing.

Python3




iterable = (1, 2, 3, 4)
iterator_obj = iter(iterable)
 
print("Iterable loop 1:")
# iterating on iterable
for item in iterable:
    print(item, end=",")
 
print("\nIterable Loop 2:")
for item in iterable:
    print(item, end=",")
 
print("\nIterating on an iterator:")
# iterating on an iterator object multiple times
for item in iterator_obj:
    print(item, end=",")
 
print("\nIterator: Outside loop")
# this line will raise StopIteration Exception
# since all items are iterated in the previous for-loop
print(next(iterator_obj))


Output:

Iterable loop 1:
1,2,3,4,
Iterable Loop 2:
1,2,3,4,
Iterating on an iterator:
1,2,3,4,
Iterator: Outside loop

Traceback (most recent call last):
  File "scratch_1.py", line 21, in <module>
    print(next(iterator_obj))
StopIteration


Previous Article
Next Article

Similar Reads

Combinatoric Iterators in Python
An iterator is an object that can be traversed through all its values. Simply put, iterators are data type that can be looped upon. Generators are iterators but as they cannot return values instead they yield results when they are executed, using the 'yield' function. Generators can be recursive just like functions. These recursive generators which
4 min read
Infinite Iterators in Python
Iterator in Python is any python type that can be used with a ‘for in loop’. Python lists, tuples, dictionaries, and sets are all examples of inbuilt iterators. But it is not necessary that an iterator object has to exhaust, sometimes it can be infinite. Such type of iterators are known as Infinite iterators. Python provides three types of infinite
2 min read
How to Compare Two Iterators in Python
Python iterators are powerful tools for traversing through sequences of elements efficiently. Sometimes, you may need to compare two iterators to determine their equality or to find their differences. In this article, we will explore different approaches to compare two iterators in Python. Compare Two Iterators In PythonBelow are the ways to compar
3 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
Article Tags :
Practice Tags :