-
Notifications
You must be signed in to change notification settings - Fork 3
/
17.iterators.py
66 lines (50 loc) · 1.23 KB
/
17.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
54
55
56
57
58
59
60
61
62
63
# python iterators
'''
__iter__(): iter()
__next__(): next()
'''
newlist = ['car','bike','cicycle']
# fist time iter fucntion 0 index ki value itervalue me store karega.
itervalue = iter(newlist)
# next ko use karke hum 0 index value ko print karegenge
print(next(itervalue))
print(next(itervalue))
print(next(itervalue))
# print(next(itervalue))
# use __iter__() and __next__()
class IterNumber:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 4:
b = self.a
self.a += 1
return b
else:
raise StopIteration
# creat objet for print values
iterobj = IterNumber()
classiter = iter(iterobj)
print(next(classiter))
print(next(classiter))
print(next(classiter))
print(next(classiter))
# print(next(classiter))
print('\n\n')
class NewIterClass:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 5:
b = self.a
self.a += 1
return b
else:
raise StopIteration
newiterObj = NewIterClass()
# iter ko use karna hai because yahi class se one by one values ko fetch karega
myvar = iter(newiterObj)
for num in myvar:
print(num)