Skip to main content

Posts

Showing posts with the label iterator

Iterator object in Python

Python iterable object The 'list' object is one of iterable objects. This makes it possible to consume its elements using a for loop. fruits = ['apple', 'orange', 'grape', 'peach'] print(type(fruits)) for elm in fruits: print(elm) # class 'list' # apple # orange # grape # peach Explicitly create a Python iterator using iter, which is a Built-in Function in Python. iter(object[, sentinel]) Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, object must be a collection object which supports the iterable protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this ...