Use the iter()
function
L = ['C++', 'Java', 'Python']
for i in iter(L):
print(i)
The iter()
function is used to create an iterator that iterates through the elements of an iterable object.
iter(iterable, sentinel[optional])
iterable |
The iterable object to iterate over. |
sentinel |
An optional value which when encountered, the StopIteration exception will be raised. |
The required iterable
argument represents the object that is to be iterated over. It can be any iterable object such as a list, tuple, string, or custom object that implements the iteration protocol.
The optional sentinel
parameter is used to specify a sentinel value that, when returned by the iterator's __next__()
method, will indicate the end of iteration.
L = [1, 2, 3, 4, 5]
for i in iter(L):
print(i)
iter with callable objects
When the iter()
function is called with a callable object that implements the iterator protocol, it creates an iterator using that object. The iterator is responsible for generating values by repeatedly calling the __next__()
method of the callable object until a specific condition is met (such as reaching the end of a sequence or encountering a sentinel value).
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
return self
def __next__(self):
if self.start < 0:
raise StopIteration
current = self.start
self.start -= 1
return current
__call__ = __next__
countdown_iterator = iter(Countdown(10))
for number in countdown_iterator:
print(number)