-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterators_example.py
More file actions
46 lines (32 loc) · 811 Bytes
/
iterators_example.py
File metadata and controls
46 lines (32 loc) · 811 Bytes
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
# Iterators
import random
t = (1, 2, 3, 4)
for x in t:
print(x)
# Iter Basics
# Lists, tuples, dictionaries and sets are all iterable objects
people = ['Bryan', 'Tammy', 'Rango']
i = iter(people)
print(i)
print(next(i))
print(next(i))
print(next(i))
# print(next(i)) # StopIteration
# Iterable class
class Lotto:
def __init__(self):
self._max = 4
def __iter__(self):
# The yield statement function's execution
# and sends a value back to the caller, but retains enough
# State to enable funtion to resume where it is left off
for _ in range(self._max):
yield random.randrange(0, 100)
def setMax(self, value):
self._max = value
print('-' * 20)
lottp = Lotto()
lottp.setMax(50)
for x in lottp:
print(x)
print('-' * 20)