AppDividend
Latest Code Tutorials

Python Iterators Tutorial With Example

0 31

Get real time updates directly on you device, subscribe now.

Python Iterators Tutorial With Example is today’s leading topic. An iterator is an object that contains the countable number of values. The iterator is an object that can be iterated upon, meaning that you can traverse through all the values inside an iterator. 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. Again, Iterators are the objects that can be iterated upon.

Python Iterators Tutorial With Example

You can build your iterator using __iter__ and __next__ methods. In Python, an iterator is an object which implements the iterator protocol, which consists of __iter__ and __next__ methods.

Iterators are everywhere in the Python-like List, Tuple, Dictionary, Set, etc. They are elegantly implemented within the for loops, comprehensions, generators, etc. but hidden in plain sight.

Iterator in Python Programming Language merely is an object that can be iterated upon. An object which will return the data, one element at a time.

Difference between Iterator and Iterable

Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from. All these objects have an iter() method which is used to get an iterator. Let’s take the example of an iterator.

# app.py

listK = ['PS4', 'XBOX360', 'PSP']
itreables = iter(listK)

print(next(itreables))
print(next(itreables))
print(next(itreables))

See the below output.

 

Python Iterators Tutorial With Example

Here, in the above code, I have defined one list and then pass the list to the iter() function. Which returns the iterator on which we can call the next() method, and it will return the one item one by one.

The __iter__ method that is called on initialization of an iterator. This should return an object that has a next or __next__ (in Python 3) method.

The __next__  method should return the next value for the iterable. When an iterator is used with a ‘for in’ loop, the for loop implicitly calls next() on the iterator object. This method should raise a StopIteration to signal the end of the iteration.

Let’s take a string as an example because strings are also iterables.

# app.py

stringK = 'KRUNAL'
itreables = iter(stringK)
print(next(itreables))
print(next(itreables))
print(next(itreables))
print(next(itreables))
print(next(itreables))
print(next(itreables))

See the following output.

 

Difference between Iterator and Iterable

Let’s see the tuple as an iterator example.

# app.py

tupleK = ('Zuck', 'Jeff', 'Bill')
itreables = iter(tupleK)
print(next(itreables))
print(next(itreables))
print(next(itreables))

See the following output.

 

tuple as an iterator

Create an Iterator in Python

If we want to create an object/class as an iterator, you have to implement the methods __iter()__ and __next()__ to your object. 

The __iter()__ method acts similar, you can do operations (initializing, etc.), but must always return the iterator object itself. The __next()__ method also allows you to do operations and must return the next item in the sequence. See the following example.

# app.py

class App:
    def __iter__(self):
        self.number = 1
        return self

    def __next__(self):
        data = self.number
        self.number += 1
        return data

IClass = App()
myiter = iter(IClass)

print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))

In the above example, I have defined one class App and then defined two methods __iter()__ and __next()__. The __iter()__ function returns the number and then __next()__ function increments the number by 1 and now see the output.

 

Create an Iterator in Python

Iterating Through an Iterator in Python

We use the next() method to manually iterate through all the elements of an iterator. When we reach at the end and there is no more data to be returned, it will raise StopIteration. Following is an example.

# app.py

my_list = [21, 19, 29, 46]
my_iter = iter(my_list)
print(next(my_iter))
print(next(my_iter))
print(my_iter.__next__())
print(my_iter.__next__())
next(my_iter)

See the below output.

 

Iterating Through an Iterator in Python

When all the items are iterated and you still want to iterate next item which is not there in the list then it will throw an exception and tell us that StopIteration.

Finally, Python Iterators Tutorial With Example is over. Thanks for taking.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.