Overview:
An iterator in Python is an object through which the elements of a container can be accessed one after another(Unless some iterators skip some elements through custom implementation). Every time a for loop in Python is used to iterate over a container like list, the for loop obtains an iterator object from the __iter__() method of the container. The for loop makes calls to the __next__() method on the iterator, until it is terminated by a StopIteration exception. These steps are performed by the for loop internally as the for loop is executed.
The built-in function iter() returns an iterator object from a container which follows the iterator protocol. As an itertaor is used internally by the for loop, the iterator obtained through the iter(), can be explicitly used for accessing the elements through various usage patterns.
Example 1:
In the Python example below, CSV data is iterated without using a for loop. Iterator is explicitly obtained through iter() function and the __next__() function is called for iteration, till the StopIteration is raised as the iterator moves past the iterable elements.
# Example Python program that obtains an iterator # Get an iterator # Move past the header of the comma separated values try: |
Output:
<class 'list_iterator'> [1, 'New York', 40.05, 1006] Skipping an invalid record [2, 'London', 50.29, 1017] [3, 'Paris', 47.05, 1017] [4, 'Dubai', 89.94, 1013] [5, 'Bengaluru', 88.57, 1016] [6, 'Singapore', 81.72, 1012] [7, 'Tokyo', 42.12, 1001] Done printing |
Example 2:
The quotes are iterated by two iterators independently to compute different analytics using the same data.
# Example Python program that creates multiple iterators dailyQuote = [["id", "scrip", "price", "qty", "yearly_high", "yearly_low"], # Do some price analytics across scrips try: scrip_id = priceIter.__next__() print("Total Price:%.2f"%priceTotal) # Do some volume analytics across scrips # Skip the first record try: id = volumeIter.__next__() # Obtain two iterators and pass on to different analytics
|
Output:
Price iterator exhausted Total Price:1261.31 Volume iterator exhausted Mean volume in millions:31.82 |
Example 3:
This Python example uses two iterables - one a list and another a set. The example iterates over both the iterables and prints the tuples using the zip() built-in function.
# Example Python program that itrates over # A Python list # A Python set - prime numbers between ten and twenty # Obtain the iterator for the list # Obtain the iterator for the set # Iterate over a list and set zipped = zip(*iterList) for i in zipped: |
Output:
('w', 11) ('x', 33) ('y', 19) ('z', 17) |