Python Forum

Full Version: is a str object a valid iterator?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
is a str object a valid iterator?
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 iterator
No, it's an iterable, but not an iterator.
(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'
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: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'.
Yes, this is one fact, that many people don't know.


for element in "abc":
    pass
is the same like

for element in iter("abc"):
    pass
The first one is implicit, the second explicit.
I use "explicit" iterators often in while-loops.
(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?