In our python learning series, we will continue some of the other modules which are going to help in learning graph. In this series, we will learn about the Iterator concept of python. Before going to an explanation about the Iterator, we need to understand what are the loops available in python. I am not going into the details of loops here because we have already gone through my last tutorial. Here is the link to explore. Conditional Control and Data Structure (List, Dictionary, and Set) of python.
Now let’s learn about the iterator of python. Iterator means executing the same block of code over and over, potentially many times something related with a loop. The question is why Iterator? while loops conditional already available in python. I would say in a simple word that If you handled with huge data, normal operations will cause trouble. Iterators or Generators take value one by one and less load on memory. In that case, we would prefer to use the Iterator.
Let’s see what are the function and keyword are available to use the iterator.
Iterator:
Use ‘iter()’ to create an iterator
‘iterkeys()’, ‘itervalues()’, ’iteritems()’ for dict
Iter.next() to read next value
Raises ‘StopIteration’ exception at the end
Raises TypeError exception is input type not supported
Generators:
Functions that work as iterators
Use ‘yeild’ function for generator
Let’s see a few examples to understand the iterator in detail. Suppose we have list and want to iterate this list by Iterator.
mylist = [1,2,3] it = iter(mylist) print it while True: print it.next()
Output :
<listiterator object at 0x7feed979a3d0> 1 2 3 Traceback (most recent call last): File "main.py", line 5, in <module> print it.next() StopIteration
So in the above example, we can see that iterator only print the item which is available in the next loop else it will be stopped. Now let us see the few examples of Iterator for the dictionary. We can iterate by key or by value or key and value both. Please see the below example.
mydict = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6} itk = mydict.iterkeys() print itk print itk.next() itv = mydict.itervalues() print itv print itv.next() itkv = mydict.iteritems() print itkv print itkv.next()
Out something like:
<dictionary-keyiterator object at 0x7f01bf5f0838> Mar <dictionary-valueiterator object at 0x7f01bf5f08e8> 3 <dictionary-itemiterator object at 0x7f01bf5f0998> ('Mar', 3)
Let’s see an example of a Generator. A generator can be defiled like this
def gen(n): for i in range(n): yield i
Example for same above definition.
g = gen(10) while True: try: print g.next() except StopIteration: break
Some of another thing or external module Collections which are related to Iterator, we can use like Collections: counter and Collections: deque. A counter is Subclass of dict for counting object which is initialization: similar to dict. Let’s explore some of the frequently used methods.
Collections: counter
Elements() : return iterator over elements
Most_common([n]): most common ‘n’ elements
Subtract([iterable]): subtracts count.
Update([iterable]): add the counts
Let’s see a few examples to understand in detail.
cnt = collections.Counter() cnt.update(['red', 'blue', 'red', 'green', 'blue', 'blue']) print cnt cnt.most_common()
Collections: Deque: (double-ended-queue)
Deque supporting stack and queue operations and Initialization collections.deque([iterable]).
Methods:
append(x): append at end
appendleft(x): append to beginning
extend([iterable]): append iterable to end
extendleft([iterable]): append to left/beginning from iterable
pop(): remove and return from end
popleft(): remove and return from beginning
Let’s see an example to understand Collection Deque.
from collections import deque d = deque('ghi') d.append('j') d.appendleft('f') print d print d.pop() print d.popleft() d.extend('jkl') print d d.extendleft('abc') print d
Output:
deque(['f', 'g', 'h', 'i', 'j']) j f deque(['g', 'h', 'i', 'j', 'k', 'l']) deque(['c', 'b', 'a', 'g', 'h', 'i', 'j', 'k', 'l'])
So we can see that the Collections Module have an awesome feature. We can also make the Collections in default Dictionary or NamedTuple or ordered dictionary. So I mean if you have Collections module then we can use default feature of python. Let us a few examples to clearly understand.
from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(11, y=22) print p print p.x, p.y Output:
Point(x=11, y=22) 11 22
An Example for orderedDict.
from collections import OrderedDict d = OrderedDict() d.update({'banana': 3}) d.update({'apple': 4}) d.update({'pear': 1, 'orange': 2}) print d print d.popitem() print d.popitem(False)
OutPut:
OrderedDict([('banana', 3), ('apple', 4), ('orange', 2), ('pear', 1)]) ('pear', 1) ('banana', 3)
Summary:
Now we have a good understanding of the Iterator and Collections module. We have seen a few examples and play around it to clear the doubts. If you still having issue or doubts then please add a comment I will try to reply as much possible. In my next python tutorial series, we will learn about the Database connections with the example.
If you are wondering to learn Android then Please Learn from Android category and Wondering to lean Kotlin then Kotlin Category will help you. If you want to learn all the python articles, then learn from the python category.
Please do subscribe your email to get the newsletter on this blog on below and if you like this post then do not forget to share like and comment on the below section.
Happy Coding 🙂
I am a very enthusiastic Android developer to build solid Android apps. I have a keen interest in developing for Android and have published apps to the Google Play Store. I always open to learning new technologies. For any help drop us a line anytime at contact@mobologicplus.com