-1

I am reading What exactly are Python's iterator, iterable, and iteration protocols? But why do we need to use "iterators"? As shown below, we can use a simple list with indexing method:

Using list

s= 'cat'

print s[0]
print s[1]
print s[2]
print s[3]

Output:

C:\Users\test\Desktop>python iterator.py
c
a
t
Traceback (most recent call last):
  File "iterator.py", line 9, in <module>
    print s[3]
IndexError: string index out of range

C:\Users\test\Desktop>

Using iterator

s = 'cat'

t = iter(s)

print next(t)
print next(t)
print next(t)
print next(t)

Output:

C:\Users\test\Desktop>python iterator.py
c
a
t
Traceback (most recent call last):
  File "iterator.py", line 36, in <module>
    print next(t)
StopIteration

C:\Users\test\Desktop>
Community
  • 1
  • 1
Kumar
  • 729
  • 3
  • 11
  • 26
  • Want to know why you should use an iterator? Type `range(10**12)` into a python 2 interpreter :P – NightShadeQueen Jul 12 '15 at 16:28
  • Yes, with trivial examples you will see very little difference. But what about large (and even *infinite*, which is perfectly possible: `def demo(): while True: yield True`) iterators? – jonrsharpe Jul 12 '15 at 16:29
  • They're also bloody useful when you have a giant file you want to read, without crashing your computer. – NightShadeQueen Jul 12 '15 at 16:38
  • @NightShadeQueen sorry still I am not clear. Why can't we use simple 'for loop' to read the file contents. how iterator will protect in this case (from crashing computer)? – Kumar Jul 12 '15 at 17:17
  • A list is fully in memory. An iterator returns values when asked and takes only its own overhead as memory. Rather than convincing you otherwise, be aware the average program probably almost never needs iterators. When they do run out of mem, the iterators allow same list behavior minus the mem use. Btw, assigning the results of an iterator, say through a list comprehension, to a list -> right back to hi mem use. – JL Peyret Jul 12 '15 at 17:32
  • @JL Peyret Thanks for your comment. Now I am somewhat clear. – Kumar Jul 13 '15 at 06:13

1 Answers1

1

In your example there's really no much difference between using an iterable and a direct access to the string object.

Iterable is a higher abstraction of behavior. It could, for example, be an object that lazily evaluates the next() item only when the function is called. Example:

class Fibonacci(object):

    def __init__(self):
        self.x = 1
        self.y = 1

    def next(self):
        tmp = self.x
        self.x = self.y
        self.y = self.y + tmp
        return tmp


if "__main__" == __name__:
    fib = Fibonacci()
    print fib.next()        
    print fib.next()        
    print fib.next()        
    print fib.next()        
    print fib.next()        
    print fib.next()        
    print fib.next()        
    print fib.next() 
    # ... and we can go like this for a long time...  

OUTPUT:

1
1
2
3
5
8
13
21
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129