is a str object a valid iterator? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: is a str object a valid iterator? (/thread-24002.html) |
is a str object a valid iterator? - Skaperen - Jan-27-2020 is a str object a valid iterator? RE: is a str object a valid iterator? - DeaD_EyE - Jan-27-2020 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. RE: is a str object a valid iterator? - perfringo - Jan-27-2020 (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' RE: is a str object a valid iterator? - DeaD_EyE - Jan-27-2020 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.
RE: is a str object a valid iterator? - perfringo - Jan-27-2020 (Jan-27-2020, 09:18 AM)DeaD_EyE Wrote: If you do 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'. RE: is a str object a valid iterator? - DeaD_EyE - Jan-27-2020 Yes, this is one fact, that many people don't know. 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. RE: is a str object a valid iterator? - Skaperen - Jan-27-2020 (Jan-27-2020, 02:13 AM)DeaD_EyE Wrote: No, it's an iterable, but not an iterator.my bad; i should have said "iterable". is it treated as an iterable by itertools.chain? |