Search code examples
pythonpython-3.xpython-2.7iteratoriterable

Using iter function inside next function


When I use the following:

s = 'hello'
for i in range(0,len(s)):
    print next(iter(s))

The code just prints h five times. But when:

s = 'hello'
s_iterable = iter(s)
for i in range(0,len(s)):
    print next(s_iterable)

All letters from hello are printed.

If in both cases iter(s) and s_iterable are iterator objects, why do they give me different results?


Solution

  • In the first one, you repeatedly call iter in your loop. When you call iter(s), it makes a new iterator for the string, and that new iterator starts from the beginning. It doesn't make sense to start from the beginning again and again. That's why you only get h's printed out.