Converting an iterator into an Object in Python:

Many situations will arise where we have to access an object like an iterator. One of the ways to do this is to form a generator loop, but, this method will extend the task and also consume more time. In Python for Data Science, we have a built-in method _iter_() for performing this task.

The function _iter_() will return an iterator for an object (set, tuple, array, etc., or custom objects). This function creates an object that is accessible element by element. For accessing the object by each element, the function _next_() is use. This is very useful when we are dealing with loops.

python data sciecne

  • Object – Here, the object whose iterator has to be created is mentioned. The object can be a collection object like a list or a user-defined object.
  • Callable, sentinel – Callable points out a callable object. Sentinel value is the value at which the iteration should terminate. The sentinel value denotes the end of the sequence, which is being iterated.

Note:

  • Calling the iterator after iteration of all elements will result in the raising of StopIteration Error.
  • The original object is not modified.

Example 1:

Example 2:

Example3:

Example 4: User defined objects.

python for data sciecne

To learn more about python for data science in detail, you can check this and this as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.