PYTHON ITERATORS
An Iterator is an object that contains a countable no. of values or elements that can be traversed.
An iterator allows a programmer to traverse through all the elements of a collection or iterable objects.
An iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().
WHAT IS THE DIFFERENCE BETWEEN ITERATOR AND ITERABLE?
Collection of elements like Lists, Tuples, Dictionaries, Strings, and Sets are all iterable objects. All these objects have an iter() method which is used to get an iterator.
Example is provided below to show that the iterator is returned, from iterable object i.e. a Tuple named fruits, by using iter() method. Iterator allows traversing on values by next() method to print each value.
Python Code
fruits = ("apple", "banana", "cherry") #Tuple-Iterable Object
myiterator = iter(fruits) #Iterator generated
print(next(myiterator))
print(next(myiterator))
print(next(myiterator))
Output
apple
banana
cherry
Leave a Reply