Let’s say we have a Python list, tuple, set, or dictionary. And, we want to iterate through the items stored in that object. One way to iterate through the stored items in the list, set, tuple, or dictionary is to use a for loop in the following way:
# A list of numbers l = [1, 2, 3, 4, 5] for i in l: print(i)
But, let’s say the data set is very large. So, if we want to keep all the items in the memory and then iterate through them, it will take lots of memory. So, we can use an iterator instead.
A Python iterator uses a lazy evaluation strategy. It delays the evaluation until the values are needed. As a result, it reduces memory footprint and makes the implementation of an algorithm more efficient when the algorithm involves a large data set.
In Python, we can use the iter() method to initialize an iterator. And, then, we can call the next() method to iterate through the items one by one.
l = [1, 2, 3, 4, 5] iterable_obj = iter(l) while True: try: item = next(iterable_obj) print(item) except StopIteration: break
Please note that the next() method returns the next element from the iterator. When there is no next element, a StopIteration …
0 Comments