-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathw3school_pythoniterators.py
More file actions
103 lines (81 loc) · 2.43 KB
/
w3school_pythoniterators.py
File metadata and controls
103 lines (81 loc) · 2.43 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# 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:
# E.g. 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))
"""
# Even strings are iterable objects, and can return an iterator:
# E.g. 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))
"""
# Looping through an iterator
# We can also use a for loop to iterate through an iterable object:
# E.g. Iterate the values of a tuple:
"""
mytuple = ("apple", "banana", "orange")
for x in mytuple:
print(x)
"""
# E.g. Iterate the characters of a string:
"""
mystr = "banana"
for x in mystr:
print(x)
"""
# Create an iterator
# To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object.
# E.g. Create an iterator that returns numbers, starting with 1, and each sequence will increase with one (returning 1,2,3,4,5 etc.):
"""
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
"""
# StopIteration
# In the __next__() method, we can add a terminating condition to raise an error if the iteration is done a specified number of times:
# E.g. Stop after 20 iterations:
"""
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
"""