Python Forum
Iterators - 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: Iterators (/thread-8999.html)



Iterators - mp3909 - Mar-16-2018

Hi,

Quick question, is "for" an iterator in python?


RE: Iterators - wavic - Mar-16-2018

Anything that has __iter__() can return an iterator.

>>> l = ['a', 'b', 'c', 'd']
>>> l_iterator = l.__iter__() # l.__iter__() returns an iterator.
>>> for ch in l_iterator:
...     print(ch)
... 
a
b
c
d
>>> type(l_iterator)
<class 'list_iterator'>
The for loop calls next(iterable, iterator, generator). I think. I don't know for sure.

>>> l = ['a', 'b', 'c', 'd']
>>> l_iterator = l.__iter__()
>>> next(l_iterator)
'a'
>>> next(l_iterator)
'b'
>>> next(l_iterator)
'c'
And so on...

You can create an iterator like this:

my_iterator = iter(l)
Then:
>>> for obj in my_iterator:
...     repr(obj)
... 
"'a'"
"'b'"
"'c'"
"'d'"



RE: Iterators - snippsat - Mar-16-2018

for is a keyword,so not an iterator.
>>> import keyword
>>> keyword.iskeyword("for")
True

# Return all keywords
>>> keyword.kwlist
for is used with iterable objects.
Also anything that can be looped over eg(string,list,dictionary,file, ect...).
# s is an iterable
>>> s = 'dog'
>>> for c in s:
...     print(c)
...     
d
o
g
>>> # t is an iterator
>>> # t has a next() method and an __iter__() method
>>> t = iter(s)
>>> next(t)
'd'
>>> next(t)
'o'
>>> next(t)
'g'
>>> next(t)
Traceback (most recent call last):
  File "<string>", line 305, in runcode
  File "<interactive input>", line 1, in <module>
StopIteration



RE: Iterators - nilamo - Mar-16-2018

(Mar-16-2018, 04:27 PM)mp3909 Wrote: Hi,

Quick question, is "for" an iterator in python?

https://docs.python.org/3/tutorial/controlflow.html#for-statements

No, it's not an iterator. It's a construct that iterates over an iterator.