ld = [1,3,5,7,9] for l in ld: print(l) # iterable can make the traversing on the collection like list, tuple, set etc, element by element # Iterable can return only one element/value at a time. print() i = 0 while i < len(ld): print(ld[i]) i+=1 ITERATOR: ========= ==> Iterator is an object which can enable the traversing on the collection like: list, tuple, dictionary etc. ==> Iterator Object, can return only one element at a item. ==> can also return the stream of data. ==> two methods: iter() ==> can return the iterator object to iterate over the data next() ==> can return the next element in the collection. d1 = iter("Hello") d2 = iter([1,3,5,7,9]) print(d1) print(d2) print(d1.__next__()) print(d1.__next__()) print(d1.__next__()) print(d1.__next__()) print(d1.__next__()) ====================================== Iterable Vs Iterator: ===================== Iterable can return only one element at a time. Iterable cannot use the memory efficiently. Iterator can return the stream of data at a time. Iterator can use the memory efficiently. data = iter(range(5)) print(data) print(data.__next__()) print(data.__next__()) print(data.__next__()) print(data.__next__()) print(data.__next__()) print(data.__next__()) =================================================== # d = 100 # for i in d: # print(i) # Iterable like: while, for cannot iterate on the integer (primitive data)object. d = iter(100) print(d) # Like iterable, iterator can also not iterate on the primitive data object. ================================================= StopIteration: ============== ==> an exception can be occurred when the number of iterations exceeded over the collection. Handling the "StopIteration" Exception: ======================================== d = iter((1,3,5,7,9)) print(d) while True: try: n = next(d) print(n) except StopIteration: break ======================================= for i in range(1,10,2): print(i) # 1 3 5 7 9 # WAP TO GENERATE ODD NUMBERS FROM THE GIVEN RANGE USING ITERATOR. class OddNumberGeneration: def __init__(self,last): self.start = -1 self.last = last def __iter__(self): return self def __next__(self): if self.start < self.last - 1: self.start += 2 # self.start = self.start + 2 # -1 + 2 = 1 3 5 7 return self.start else: raise StopIteration obj = OddNumberGeneration(10) while True: try: x = next(obj) print(x) except StopIteration: break