Reputation: 1
I want to ask how is the iterator in python designed? I have read that when the iterator is used it returns single values of the sequence of an iterable it represents upon the call of next or next(). And this way it does not need to copy the full iterable and therefore occupy memory. Exactly how can you return single values of a sequence object like list, string or mapping objects like dictionaries? Does it store pointers to the original sequence datastructure contents and then have a method called next which increments the pointer?
Thanks
In Python 3, however, zip() returns an iterator. This object yields tuples on demand and can be traversed only once. The iteration ends with a StopIteration exception once the shortest input iterable is exhausted. If you supply no arguments to zip(), then the function returns an empty iterator:
Upvotes: 0
Views: 793
Reputation: 531125
An iterator is just a class that defines __next__
. That's it (though all iterators should also be iterable by defining __iter__ = lambda self: self
as well). It's entirely how __next__
is defined that defines the behavior of the iterator.
You can create an iterator over a constant sequence
class Ones:
def __iter__(self):
return self
def __next__(self):
return 1
or you can create an iterator that walks through some iterable value. It's the iterator that keeps track of which value to return next, from the values supplied by the iterable. Here's a simplified version of list_iterator
, which is the built-in type of which list.__iter__
return values.
class list_iterator:
def __init__(self, lst):
self.lst = lst
self.i = 0
def __iter__(self):
return self
def __next__(self):
if self.i == len(self.lst):
raise StopIteration
x = self.lst[self.i]
self.i += 1
return x
x = [1,2,3]
# prints 1, then 2, then 3
for v in list_iterator(x):
print(v)
Upvotes: 2