Join my course at Udemy (Python Programming Bible-From beginner to advanced )

Blogger templates

Monday 25 May 2020

Iteration



Python provides various ways to iterate over sequences and perform repetition tasks. for and while loop provides the way to iterate, range, zip, enumerate and map are specialized function to loop through sequences. 

In the similar line, iterator provides simpler way to loop through sequences and it provides faster alternative as it runs at C language speed.

What is iteration object ?

A object is a iteration object if it has following two functionality :
- Object with __next__ method to advance to next result.
- Object that raises ‘StopIteration’  exception at the end of the series.

In python, a file object is an iteration object by default. Following examples show how file object can be used as iterator to browse the file.

File object as iterator object.

In the following example we can see that file object (f) is a iterator object and hence True is returned. 

f= open("HelloPython.py")
iter(f) is f
True

As explained above, if file object is a iterator object then
- We should be able to use f.__next__ to traverse through the file.
- And when end of file is reached then "StopIteration" exception should be raised.

Following example shows the implementation of __next__ function of file as a iterator object. Note that "HelloPython.py" has three line and we can traverse the file line by line using __next__ function of iterator.

f = open("HelloPython.py")
print(f.__next__())
print(f.__next__())
print(f.__next__())
Hello Python-1
Hello Python-2
Hello Python-3

As HelloPython.py  file has just three lines, the next call of f.__next__() should raise "StopIteration" exception.

print(f.__next__())

 StopIteration                             Traceback (most recent call last)
<ipython-input-29-db2988a815ca> in <module>()
    ---> 12 print(f.__next__())
StopIteration:


Using next(f) instead of __next__() 

Python provides next function that internally calls __next__() function. This way we can use neater function to loop through the file. 

f = open("HelloPython.py")
print(next(f))
print(next(f))
print(next(f))

Hello Python-1
Hello Python-2
Hello Python-3


Iteration of file object with for Loop

Above example shows the traversal of file object is not a neater way as  calling next() or __next__  function every time is cumbersome. As shown the example below, for loop provides easier way where calling __next__() function and checking for StopIteration function is automatically checked. 

for line in open("HelloPython.py"):
    print(line)
Hello Python-1
Hello Python-2
Hello Python-3

List and Dictionary as iterator

By default list and dictionary are not a iterator object but it is possible to change the them to a iterable object using the iter function as shown below.

Following code shows how to change the list object to an iterator and then use that in for and while  to loop through the sequence object.

##List Iterator – with while loop
L=[1,2,3,4]
I=iter(L) ## change the list to iterator
while True:
    try:
        nextElem = next(I)
    except StopIteration:
        break;
    print (nextElem)
1
2
3
4

##List iterator -- Using FOR Loop
L=[1,2,3,4]
for x in L:  ##changes to iterator and traverses list element
    print(x)
1
2
3
4


In the similar way it is possible to change dictionary to iterator object and then traverse the dictionary object. Following example shows the use of dictionary iterator with for and while loop.

D = {"first":1, "second":2, "third":3}
I=iter(D)
while True:
    try:
        nextElem = next(I)
    except StopIteration:
        break;
    print (nextElem, end=",")
first, second, third,


##Dictionary Iterator
D = {"first":1, "second":2, "third":3}
for x in D:
    print (x, end=",")
first, second, third,
The above example shows how to convert list and dictionary to an iterator using iter  function This function can be used to change other python datatype to a iterator and then use the iterator to traverse the object.

Conclusion

In the post we have gone through iterator that can be used as an alternative to have a neater and faster way to traverse through the python object. In the next post we will go through comprehension that is another way to traverse through python object.
Share:

0 comments:

Post a Comment

Feature Top (Full Width)

Pageviews

Search This Blog