An iterator is an object that contains a countable number of values. An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().
Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.
All these objects have an iter() method which is used to get an iterator:
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit)) # apple
print(next(myit)) # banana
print(next(myit)) # cherry
Strings are also iterable objects, containing a sequence of characters:
mystr = "banana" myit = iter(mystr)print(next(myit)) # b print(next(myit)) # a print(next(myit)) # n
We can also use a for loop to iterate through an iterable object. The for loop actually creates an iterator object and executes the next() method for each loop automatically.
mytuple = ("apple", "banana", "cherry")
for x in mytuple:
print(x)
Which two methods represent the Iterator protocol in Python?