Reputation: 13
I am trying to build an iterator using its native functions iter() and next(). But the code I written is not iterating until end. it reads only the first charecter. what wrong I have done on the code.
def itera(x):
while True:
it = iter(x)
return (next(it))
print(itera([1,2,3,4,5]))
Upvotes: 0
Views: 46
Reputation: 1331
Because you re-create iterator with it = iter(x)
. Put it outside of the loop. Even so it will not work the way you expect because of return statement, which stops execution after the first element. Rather you need generators:
def itera(x):
it = iter(x)
while True:
yield (next(it))
print(list(itera([1,2,3,4,5])))
Upvotes: 1