Learn Python Itertools and Python Iterables with Examples
Free Python courses with 57 real-time projects - Learn Python
1. Python Itertools and Python Iterables
All the constructs of Python programming, all the syntactic sugar. These are just a few good things about Python. We’ve talked earlier of Iterators, Generators, and also a comparison of them. Today, we will talk about Python iterables, examples of iterables in python, Python Itertools, and functions offered by Itertools in python.
So, let’s start exploring Iterables & Itertools in Python Programming Langauge.
2. What is Python Iterables?
An iterable in python is an object in python that can return an iterator. Using this python iterator, we can iterate on every single element of the iterable.
To check what happens internally in an iterator, we’re going to use the ‘dis’ module to disassemble the code. Once we import it, we call the dis() function. Before Preferring the example, let’s see python Syntax.
>>> import dis >>> dis.dis('for _ in [1,2,3]:pass')
1 0 SETUP_LOOP 12 (to 14)
2 LOAD_CONST 4 ((1, 2, 3))
4 GET_ITER
>> 6 FOR_ITER 4 (to 12)
8 STORE_NAME 0 (_)
10 JUMP_ABSOLUTE 6
>> 12 POP_BLOCK
>> 14 LOAD_CONST 3 (None)
16 RETURN_VALUE
Here, GET_ITER is like invoking iter(). Likewise, FOR_ITER is to repeatedly call next() to get each element.
3. Example of Python Iterables
Okay, so let’s take an example before we begin.
>>> nums=[1,2,3] >>> number=iter(nums) >>> next(number)
1
>>> next(number)
2
>>> next(number)
3
>>> next(number)
Traceback (most recent call last):
File “<pyshell#224>”, line 1, in <module>
next(number)
StopIteration
In this code, ‘nums’ is a python iterables. Using the function iter(), we create an iterator ‘number’. This relationship can be inferred from the following representation.
An iterables in python has the methods __len__() and __getitem__()
>>> a=[1,2,3] >>> dir(a)
[‘__add__’, ‘__class__’, ‘__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’]
>>> a.__len__()
3
>>> a.__getitem__(2)
3
While __len__() returns the length of the python iterables, __getitem__() takes an index as an argument, and returns the value at that position in the iterable in python.
4. More Iterables in Python
Most containers are python iterables. Let’s see some relationship using the built-in function issubclass().
>>> import collections >>> issubclass(collections.Iterator,collections.Iterable)
True
#This means an iterator is a python iterable.
>>> issubclass(collections.Iterable,collections.Iterator)
False
>>> issubclass(collections.Generator,collections.Iterator)
True
#A generator is a Python iterator
>>> issubclass(collections.Generator,collections.Iterable)
True
#So, a generator is also an iterable in python
Let’s check for some more constructs.
>>> issubclass(collections.Set,collections.Iterable)
True
#A set is a python iterable
>>> issubclass(collections.UserDict,collections.Iterable)
True
>>> issubclass(collections.deque,collections.Iterable)
True
>>> issubclass(collections.deque,collections.Iterable)
True
>>> issubclass(collections.defaultdict,collections.Iterable)
True
>>> issubclass(collections.OrderedDict,collections.Iterable)
True
When we say that an iterator is a python iterable, we mean it. In the following code, we define an iterator, and then call the iter() function on it.
>>> a=iter([1,2,3]) >>> b=iter(a) >>> b
<list_iterator object at 0x0328BCB0>
>>> a
<list_iterator object at 0x0328BCB0>
>>> next(b)
1
>>> next(a)
2
>>> next(b)
3
>>> next(a)
Traceback (most recent call last):
File “<pyshell#242>”, line 1, in <module>
next(a)
StopIteration
What we get back is a python iterator. Hence, an iterator is python iterable. In this code, hence, b and a reference to the same iterator. Thus, when we call next() on either one, the state is changed for both.
5. Python Itertools
Python itertools is a module we can use as a standard library for functional programming. We’ll see some of the functions it offers. First, let’s talk about count().
a. count() in Python Itertools
The function count() in python Itertools takes, as an argument, an integer number to begin count at. It then counts infinitely, unless we break out of the for-loop using an if-statement.
>>> from itertools import count >>> for i in count(7): if i>14: break print(i)
7
8
9
10
11
12
13
14
Let’s try calling it without an argument and without a terminating if-condition.
>>> for i in count(): print(i)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Traceback (most recent call last):
File “<pyshell#265>”, line 2, in <module>
print(i)
KeyboardInterrupt
>>>
Here, we had to press Ctrl+C to interrupt this infinite iterator. We can also give it a positive/ negative interval as a second argument.
>>> for i in count(2,2): if i>10: break print(i)
2
4
6
8
10
Now, let’s see another function.
b. cycle() in Python Itertool
Cycle() function in python itertools infinitely iterates over a python iterables, unless we explicitly break out of the loop.
>>> from itertools import cycle >>> c=0 >>> for i in cycle(['red','blue']): if c>7: break print(i) c+=1
red
blue
red
blue
red
blue
red
blue
c. repeat() in Python Itertool
This one repeats an object infinitely unless explicitly broken out of.
>>> from itertools import repeat >>> c=0 >>> for i in repeat([1,2,3]): if c>7: break print(i) c+=1
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
We can also specify the number of times we want it to repeat, as a second argument.
>>> for i in repeat([1,2,3],4): print(i)
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
So, this was all about Python Iterables and Itertools. Hope you like our explanation.
6. Conclusion
Now, we know that a Python iterables are an object that we can iterate on. Likewise, an iterator is a python object that lets us iterate on an iterator. We also saw the relationships between various classes of a collection. Finally, we took a brief look at the module ‘itertools’.
Still, have a confusion, feel free to approach us through the comment box!
See Also-
Did you like this article? If Yes, please give DataFlair 5 Stars on Google