Computer >> Computer tutorials >  >> Programming >> Python

Difference between Python iterable and iterator


An iterable can be loosely defined as an object which would generate an iterator when passed to in-built method iter(). There are a couple of conditions, for an object to be iterable, the object of the class needs to define two instance mehtod: __len__ and __getitem__. An object which fulfills these conditions when passed to method iter() would generate an iterator.

Let’s understand the below example, to understand the iterable −

string = "Tutorialspoint"
for char in string:
print (char)

Output

T
u
t
o
r
i
a
l
s
p
o
i
n
t

Above the code use the __getitem__(index) method which would return the element at the position specified by index.

So, our above code −

  • Start with index 0
  • Call string.__getitem__(index)
  • IndexError raised? Stop
  • The run body of the loop
  • Increment index, revert back to step 2.

Iterators

Iterators are defined as an object that counts interation via an iternal state variable. The variable, in this case, is NOT set to zero when the iteration crosses the last item, instead, StopIteration() is raised to indicate the end of the iteration. This also means that iterated item will be iterated once only, like in below example −

my_list = ['itemOne', 'TutorialsPoints']
iterators_of_some_list = iter(my_list)
for i in iterators_of_some_list:
   print(i)
for j in iterators_of_some_list: # doesn't work
   print(j)
#However
for k in my_list:
   print(k)
for l in my_list: # it worked
   print(l)

Output

itemOne
TutorialsPoints
itemOne
TutorialsPoints
itemOne
TutorialsPoints

Above code holds true because the iter() method on the iterator returns itself (is to remember the current state). So above we have a loop kind of implementation similar to “for” to terminate it.