+ 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)

6th Jul 2021, 3:14 PM
Zahed Shaikh
Zahed Shaikh - avatar
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.
6th Jul 2021, 4:57 PM
Lothar
Lothar - avatar
+ 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
6th Jul 2021, 3:31 PM
visph
visph - avatar
+ 1
Lothar Brilliantly stated addendum! I wonder what the ratio is of those working with Python who understand this about the Python for loop. I suspect it's low. So it's always good to re[iter]ate. đŸ˜‰đŸ€ŁđŸ˜œ
6th Jul 2021, 7:19 PM
David Carroll
David Carroll - avatar
0
visph Brilliantly answered!
6th Jul 2021, 4:51 PM
David Carroll
David Carroll - avatar