Python Itertools and Python Iterables
Malini Shukla
Senior Data Scientist || Hiring || 6M+ impressions || Trainer || Top Data Scientist || Speaker || Top content creator on LinkedIn || Tech Evangelist
Introduction to 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 Example of Java Iterables
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.
Top books to learn Python Programming Language.
See Also-