Iterator VS Generator in python
Iterator :
- Object
- Contain iterable objects ( List, tuple , set)
- used iter() and next() function
- iter() containing an iterable object (List tuple ,set)
- next() call next element in the iterable object
- Lazy evaluation
list_iterObj = iter(['Ram', 'Shyam',' Mohan']) # Contain iterable objects ( List only)
print(list_iterObj ) # output <list_iterator object at 0x000001DA2D7A2B00>
# Therefore we use the next() function or loop
print(next(list_iterObj )) # output Ram only
print(next(list_iterObj )) # then output Shyam only lazy evaluation
# loop
for item in list_iterObj:
print(item)
#output you can guess :)
Generator :
- Create iterators
- It is used function but doesn't return a Type
- used yield keyword
- lazy evaluation
- it is a generator object
- used next() function to print the next item
def number(n):
for i in range(1, n+1):
yield i*i # used yield keyword it is property of the generator
# generator object
gen_obj = number(5)
print(gen_obj) # output <generator object number at 0x000001B0EC1760A0>
#we have 2 options use next() function or loop
print(next(gen_obj )) # output 1
print(next(gen_obj )) # output 4
# use loop
for val in gen_obj:
print(val) # guess answer and comment
Comments
Post a Comment