-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiterators.py
53 lines (37 loc) · 1.01 KB
/
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 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.
# 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))
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
# looping
mytuple = ("apple", "banana", "cherry")
for x in mytuple: # The for loop actually creates an iterator object and executes the next() method for each loop.
print(x)
# custom iteration
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
i = self.a
self.a += 1
return i
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)