The iter() method returns the iterator for the provided object. The iter() method creates the object which can be iterated one element at a time.
Python iter
Python iter() is a built-in function that converts an iterable to an iterator. It offers another way to iterate the container. To access iter() function’s elements. iter() uses next() for obtaining values.
These objects are useful when we couple with the loops like for loop and 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 the iteration count cannot be reassigned to 0.
Therefore, it can be used to traverse a container just once.
Syntax
The syntax of the iter() method is the following.
iter(object, sentinel)
Parameters
Object: It is an object whose iterator must be created (can be set, tuple, list, dictionaries, etc.).
sentinel (Optional) – It is the special value 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))
We passed a list to the iter() function in the above code and printed the item 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 explicit or implicit loop to go over the group of items that is an iteration.
In Python, iterable and iterator have precise meanings.
The iterable is an object with an __iter__ method that returns an iterator or 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, map, or list comprehension, etc.,
In Python, the next() method is called automatically to get all items from an iterator, going through the iteration process.
That’s it for this tutorial.
Thanks for the post