-
Notifications
You must be signed in to change notification settings - Fork 0
/
18.Iterators.py
36 lines (26 loc) · 880 Bytes
/
18.Iterators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
"""
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__().
"""
# 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
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
# Even strings are iterable objects, and can return an iterator
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))