+ 1
What is iter function in python? What is next function?
s='abc' i=iter(s) print(i) next(i) print(next(i)) print(s)
4 Answers
+ 8
Zahed Shaikh ,
a short additional comment to visph's explanations .
when using a for loop for iteration, user has not to take care about when the end of the sequence is reached. by using the next() function when the last element of the sequence is already reached, a StopIteration exception is raised, and the program will be terminated prematurely.
+ 7
iter takes an iterable and return a generator iterating it...
next takes an iterable and return next value...
if generator is provided to next function, one value is consumed (returned) and so next use of generator will no more generate that value (a generatir can be iterated only once)
l = [ 1, 2, 3, 4 ]
print(next(l)) # 1
print(next(l)) # 1
for v in l:
print(v) # 1, 2, 3, 4
g = iter(l)
print(next(g)) # 1
print(next(g)) # 2
for v in g:
print(v) # 3, 4
0
visph Brilliantly answered!