Python Iterators

Python Iterators || Iterators in Python

  • An iterator is an object that holds a countable number of values. In this tutorial, you will learn how iterator works and how we can create user define iterator.
Python Iterators

Iterators in Python

  • In Python and we are using iterator in many places. They are elegantly implemented within for loops, comprehensions, generators etc. but are hidden in plain sight.
  • An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. An object which will return data, one element at a time.
  • Technically, we can say that an iterator is an object in Python which implements the iterator protocol. Which consist of the methods __iter__() and __next__().

Iterator vs Iterable

  • The Iterable is an object in which we can iterate values ​​one by one. Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.
  • All Iterable objects have a iter() method which is used to get an iterator:
  • By passing iterable object as an argument in iter() method and this method will return you iterator object by which you can iterate value one by one.
  • The iter() function (which in turn calls the __iter__() method) returns an iterator from them.

Looping Through an Iterator

We use for statement for looping over a list.

list1=[10,20,30,40,50]

for i in list1:

    print(i)

output:

10

20

30

40

50

If we use it with a string, it loops over its characters.

for c in “python”:

    print(c)

output:

p

y

t

h

o

n

So, there are many types of objects which can be used with a for loop. These are called iterable objects.

Iterating Through an Iterator

  • The built-in function iter() takes an iterable object and returns an iterator.
  • By passing iterable object as an argument in iter() method we can get iterator

     object.

  • After getting iterator object if we call __next__ () method on that iterator  

     object we can get next value of that iterator object.

  • We can also use the next() function to manually iterate through all the items of an iterator.

Example:

# define a list

nums=[10,20,30,40,50]

# get an iterator using iter()

it = iter(nums)

# iterate through it by calling __next__() on it

print(it.__next__())# Output: 10

print(it.__next__())# Output: 20

print(it.__next__())# Output: 30

print(it.__next__())# Output: 40

print(it.__next__())# Output: 50

print(it.__next__())# This will raise error, no items left

output:

10

20

30

40

50

print(it.__next__())# This will raise error, no items left

StopIteration

Example:

# define a list

nums=[10,20,30,40,50]

# get an iterator using iter()

it = iter(nums)

# iterate through it by calling next() on it

print(next(it))# Output: 10

print(next(it))# Output: 20

print(next(it))# Output: 30

print(next(it))# Output: 40

print(next(it))# Output: 50

print(next(it))# This will raise error, no items left

output:

10

20

30

40

50

print(it.__next__())# This will raise error, no items left

StopIteration

How to Create User define Iterable Object

  • It is also possible to create user define iterable object before it what we have seen that is built in iterator object they having function which is next tried it and will function as you
  • Suppose we want to print the top 10 values not all one by one right to achieve that here we can create a class and will have this class name as Top10. I want to specify the value I want to have a counter right for that I will use __init__ () function where i defined my counter variable

 def __init__(self):

        self.num=1

  • If you want to create your own a iterator you need to define two important method the first one is iter() a method.
  • iter() will give you the object of iterator and second you need to define is next() method   which will give you the next value or next object .

Here, we show an example that will give us the Top 10 values in each iteration.

  • so let’s we define __iter__() function which will give you the object  so it will simply return self.
  • now we define another method __next__() which will simply return next value.
  • so in our example we want to next value of num.
  • first of all we are using  a variable val in which I will assign this value self.num now and then I also want to increment by one because when you give one for the next iteration you want to 2 and next iteration you want 3 so we can say simply self.num+=1 and return the value of val not num because this is incremented
  •  this is why they can do that and then return the value of well ok not because it is incremented.

class Top10:

    def __init__(self):

        self.num=1

    def __iter__(self):

        return self

    def __next__(self):

        val=self.num

        self.num+=1

        return val

so this is iterator . this  Top10 is iterator if you want to prove let’s do it .

#Creating Top10 Iterator object which has those values

values=Top10()

#Iterate the values of a Top10 Iterator using loop:

for i in values:

    print(i)

let’s see what happened to when you run this code and look at the output hold down actually we want Top10 values but here we gotted thousands of values and now we stop the program forcefully by pressing stop button

now we void the for loop and  just we try to understand what is happening with just one value to check if everything is working  or not for that we are using __next__() or  otherwise you can use next() method.

class Top10:

    def __init__(self):

        self.num=1

    def __iter__(self):

        return self

    def __next__(self):

        val=self.num

        self.num+=1

        return val

#Creating Top10 Iterator object which has those values

values=Top10()

#Iterate the first values of a Top10 Iterator

print(values.__next__())

#Iterate the second values of a Top10 Iterator

print(values.__next__())

this will work but what is wrong with loop problem  with loop is that loop will go start to end and we are assuming that end with 10 but no val is mention that is stop at 10.

class Top10:

    def __init__(self):

        self.num=1

    def __iter__(self):

        return self

    def __next__(self):

        if self.num<=10:

            val=self.num

            self.num+=1

            return val

#Creating Top10 Iterator object which has those values

values=Top10()

#Iterate the values of a Top10 Iterator using loop:

for i in values:

    print(i)

None

None

None

None

None

None

None

None

None

None

None

None

…….

so now you can see something went wrong in this code. so what’s happening actually we want top 10 values but after that the loop is still running we don’t want I want to stop a loop right so to stop a loop what I will do it we will write the else condition if it is going beyond that you simply raise the exception because the only way to stop for loop is to raise exception is no other way and it handles that accepts an internally so for loop has the power to stop this.

class Top10:

    def __init__(self):

        self.num=1

    def __iter__(self):

        return self

    def __next__(self):

        if self.num<=10:

            val=self.num

            self.num+=1

            return val

        else:

            raise StopIteration

We can use a for loop to iterate over our iterator class.

#Creating Top10 Iterator object which has those values

values=Top10()

#Iterate the values of a Top10 Iterator using loop:

for i in values:

    print(i)

output:

1

2

3

4

5

6

7

8

9

10

class Top10:

    def __init__(self):

        self.num=1

    def __iter__(self):

        return self

    def __next__(self):

        if self.num<=10:

            val=self.num

            self.num+=1

            return val

        else:

            raise StopIteration

# create an object

values = Top10()

# create an iterable from the object

i = iter(values)

# Using next to get to the next iterator element

print(next(i))

print(next(i))

print(next(i))

print(next(i))

print(next(i))

Leave a Comment

Your email address will not be published. Required fields are marked *