Python iter: How to Convert Iterable to Iterator
Python iter() is an inbuilt function that is used to convert an iterable to an iterator. It offers another way to iterate the container i.e access its elements. iter() uses next() for obtaining values. The iter() method returns the iterator for the provided object. The iter() method creates the object which can be iterated one item at a time.
Python iter() Example
These objects are useful when we coupled with the loops like for loop, while loop.
The iteration object remembers an iteration count via an internal count variable.
Once the iteration is finished, it raises the StopIteration exception and iteration count cannot be
reassigned to 0.
Therefore, it can be used to traverse a container just once.
The syntax of the iter() method is the following.
iter(object, sentinel)
object – It is an object whose iterator has to be created (can be sets, tuples, lists, dictionaries, etc.)
sentinel (Optional) – It is the special value that is used to represent the end of a sequence.
See the following example.
# app.py data = iter(['millie', 'finn', 'gaten', 'caleb']) print(next(data)) print(next(data)) print(next(data)) print(next(data))
In the above code, we have passed a list to the iter() function and then print the item one by one using the Python next() function.
#How iter() works for custom objects
Okay, now let’s define the custom object and then iterate that object using the next() function.
# app.py class Display: def __init__(self, count): self.count = count def __iter__(self): self.data = 0 return self def __next__(self): if(self.data >= self.count): raise StopIteration self.data += 1 return self.data num = Display(2) printData = iter(num) # prints '1' print(next(printData)) # prints '2' print(next(printData)) # raises StopIteration print(next(printData))
See the output.
➜ pyt python3 app.py 1 2 Traceback (most recent call last): File "app.py", line 26, in <module> print(next(printData)) File "app.py", line 11, in __next__ raise StopIteration StopIteration ➜ pyt
Iteration is a generic term for taking each element of something, one after another. Any time you use the loop, explicit or implicit, to go over the group of items, that is an iteration.
In Python, iterable and iterator have precise meanings.
The iterable is an object that has an __iter__ method that returns an iterator, or which describes the __getitem__ method that can take the sequential indexes starting from zero (and raises an IndexError when the indexes are no longer valid).
So the iterable is an object that you can get an iterator from.
An iterator is an object with a next (Python 2) or __next__ (Python 3) method.
Whenever you practice a for loop, or map, or a list comprehension, etc. in Python, the next() method is called automatically to get all items from an iterator, therefore going through the process of iteration.
Finally, Python iter() Example Tutorial is over.
Thanks for the post