The iter() function is used to create an iterator object from an iterable object. The next() function is used to get the next value in an iterator. When there are no more values to return, the next() function raises the StopIteration exception.
Here is an example of using the iter() and next() functions with an iterator that prints numbers from 0 to 4:
class MyIterator:
def __init__(self):
self.numbers = [0, 1, 2, 3, 4]
self.current_index = 0
def __iter__(self):
return self
def __next__(self):
if self.current_index >= len(self.numbers):
raise StopIteration
result = self.numbers[self.current_index]
self.current_index += 1
return result
iterator = MyIterator()
my_iter = iter(iterator)
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
print(next(my_iter))
Output:
0
1
2
3
4