The object that produces successive items or values from its associated iterable
Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__()
Lists, tuples, dictionaries, sets & string are all iterable objects. They are iterable containers which you can get an iterator from
All these objects(Lists, tuples, dictionaries, sets & String) have a iter() method which is used to get an iterator
In below example, return an iterator from a list, and print each value:
mylist = ["one", "two", "three"] myit = iter(mylist) print(next(myit)) #Output: one print(next(myit)) #Output: two print(next(myit)) #Output: three |
The for loop actually creates an iterator object and executes the next() method for each loop
mylist = ["one", "two", "three"] for x in mylist: print(x) |
one two three |
mylist = ["one", "two", "three"] myit = iter(mylist) for x in myit: print(x) |
one two three |
Above both examples displays the same output since 'for' loop and 'iter' & 'next' methods are iterate through\from an iterable object
let's do a quick review these terms
Term | Meaning |
---|---|
Iteration | The process of looping through the objects or items in a collection |
Iterable | An object (or the adjective used to describe an object) that can be iterated over |
Iterator | The object that produces successive items or values from its associated iterable |
iter() | The built-in function used to obtain an iterator from an iterable |
If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!