Jan-27-2020, 02:06 AM
Jan-27-2020, 02:13 AM
In [1]: next('Foo') --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-1-60a92f7bb96c> in <module> ----> 1 next('Foo') TypeError: 'str' object is not an iteratorNo, it's an iterable, but not an iterator.
Jan-27-2020, 08:54 AM
(Jan-27-2020, 02:13 AM)DeaD_EyE Wrote: [ -> ]No, it's an iterable, but not an iterator.
..and to make iterator from iterable there is built-in function iter():
>>> next(iter('42')) '4'
Jan-27-2020, 09:18 AM
Yes, but you should have a reference to the iterator:
greeting = "Hello World" iterator = iter(greeting) print(next(iterator)) print(next(iterator))If you do
next(iter('42'))
two times, you'll get 4 two times.Jan-27-2020, 09:44 AM
(Jan-27-2020, 09:18 AM)DeaD_EyE Wrote: [ -> ]If you do next(iter('42'))
two times, you'll get 4 two times.
Yes, you are absolutely right. There is ambiguity in my post, it was too much about next() and not about practical application.
Just to add one more tidbit: for-loop creates iterator from iterable 'behind the scenes'.
Jan-27-2020, 10:54 AM
Yes, this is one fact, that many people don't know.
I use "explicit" iterators often in while-loops.
for element in "abc": passis the same like
for element in iter("abc"): passThe first one is implicit, the second explicit.
I use "explicit" iterators often in while-loops.