pythoniterator

Iterate over an object that is not an iterator


I'm not sure why I can iterate over an object that is not an iterator?

>>> import spacy                                           
>>> nlp = spacy.load("en_core_web_sm")                     
>>> doc = nlp("Berlin looks like a nice city")             
>>> next(doc)                                              
Traceback (most recent call last):                         
  File "<stdin>", line 1, in <module>                      
TypeError: 'spacy.tokens.doc.Doc' object is not an iterator
>>> for token in doc:                                      
...     print(token)                                       
...                                                        
Berlin                                                     
looks                                                      
like                                                       
a                                                          
nice                                                       
city  

Solution

  • Relevant part from python docs:

    When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop.

    So yes, for call iter() on an iterable to obtain an iterator