What is the most basic definition of \"iterable\", \"iterator\" and \"iteration\" in Python?
I have read multiple definitions but I am unable to identify the exact m
Iterable:- something that is iterable is iterable; like sequences like lists ,strings etc.
Also it has either the __getitem__
method or an __iter__
method. Now if we use iter()
function on that object, we'll get an iterator.
Iterator:- When we get the iterator object from the iter()
function; we call __next__()
method (in python3) or simply next()
(in python2) to get elements one by one. This class or instance of this class is called an iterator.
From docs:-
The use of iterators pervades and unifies Python. Behind the scenes, the for statement calls iter()
on the container object. The function returns an iterator object that defines the method __next__()
which accesses elements in the container one at a time. When there are no more elements, __next__()
raises a StopIteration exception which tells the for loop to terminate. You can call the __next__()
method using the next()
built-in function; this example shows how it all works:
>>> s = 'abc'
>>> it = iter(s)
>>> it
>>> next(it)
'a'
>>> next(it)
'b'
>>> next(it)
'c'
>>> next(it)
Traceback (most recent call last):
File "", line 1, in
next(it)
StopIteration
Ex of a class:-
class Reverse:
"""Iterator for looping over a sequence backwards."""
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
>>> rev = Reverse('spam')
>>> iter(rev)
<__main__.Reverse object at 0x00A1DB50>
>>> for char in rev:
... print(char)
...
m
a
p
s