Thursday, 23 September 2021

Python: iterators in python

What is iterable?

Anything you can loop over is called an iterable, for example, list is an iterable. In technical terms, any object which implements __iter()__ method is called as iterable.

 

Let’s confirm the same by printing all the methods, attributes of a list.

 

dir_demo.py

primes = [2, 3, 5, 7]

print(dir(primes))

Output

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

As you see above output, list has this special method __iter__.

 

What is iterator?

Iterator is an object, that iterate over an iterable and return the object one at a time. Iterator provides __next__() method which returns the next value in the iteration.

 

You can get the iterator instance by calling __iter__ method of an object.

 

Iterate over a list using __iter__ method

 

iterate_over_a_list.py

primes = [2, 3, 5, 7, 11]

primes_iterator = primes.__iter__()

while(True):
    try:
       next_ele =  primes_iterator.__next__()
       print(next_ele)
    except StopIteration:
        break

Output

2
3
5
7
11

You can even use built-in functions iter(), next() to get the iterator, and next element of the iterator.

 

iterate_over_a_list_2.py

primes = [2, 3, 5, 7, 11]

primes_iterator = iter(primes)

while(True):
    try:
       next_ele =  next(primes_iterator)
       print(next_ele)
    except StopIteration:
        break

Output

2
3
5
7
11




Previous                                                    Next                                                    Home

No comments:

Post a Comment