Page 443 - CITS - Computer Software Application -TT
P. 443
COMPUTER SOFTWARE APPLICATION - CITS
Iterators, Modules, Dates, Math
Python Iterators
• An iterator is an object that contains a countable number of values.
• An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
• Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the
methods __iter__() and __next__().
Iterator vs Iterable
Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an
iterator from.
All these objects have a iter() method which is used to get an iterator:
Example: Get your own Python Server
Return an iterator from a tuple, and print each value:
mytuple = (“apple”, “banana”, “cherry”)
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
OUTPUT
APPLE
BABANA
CHERRY
Even strings are iterable objects, and can return an iterator:
Example:
Strings are also iterable objects, containing a sequence of characters:
mystr = “banana”
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
OUTPUT
B
A
N
A
N
A
430
CITS : IT&ITES - Computer Software Application - Lesson 120 - 137