Skip to content

Commit 588f067

Browse files
committed
Iterators Tutorial
1 parent 9e4da1f commit 588f067

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
class Sentence:
3+
4+
def __init__(self, sentence):
5+
self.sentence = sentence
6+
self.index = 0
7+
self.words = self.sentence.split()
8+
9+
def __iter__(self):
10+
return self
11+
12+
def __next__(self):
13+
if self.index >= len(self.words):
14+
raise StopIteration
15+
index = self.index
16+
self.index += 1
17+
return self.words[index]
18+
19+
20+
def sentence(sentence):
21+
for word in sentence.split():
22+
yield word
23+
24+
25+
my_sentence = sentence('This is a test')
26+
27+
# for word in my_sentence:
28+
# print(word)
29+
30+
print(next(my_sentence))
31+
print(next(my_sentence))
32+
print(next(my_sentence))
33+
print(next(my_sentence))
34+
print(next(my_sentence))
35+
36+
37+
# This should have the following output:
38+
# This
39+
# is
40+
# a
41+
# test

Python/Iterators/iter-demo.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
2+
class MyRange:
3+
4+
def __init__(self, start, end):
5+
self.value = start
6+
self.end = end
7+
8+
def __iter__(self):
9+
return self
10+
11+
def __next__(self):
12+
if self.value >= self.end:
13+
raise StopIteration
14+
current = self.value
15+
self.value += 1
16+
return current
17+
18+
19+
def my_range(start):
20+
current = start
21+
while True:
22+
yield current
23+
current += 1
24+
25+
26+
nums = my_range(1)
27+
28+
for num in nums:
29+
print(num)

0 commit comments

Comments
 (0)