Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Iterators
#1
Hi,

Quick question, is "for" an iterator in python?
Reply
#2
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'"
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
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
Reply
#4
(Mar-16-2018, 04:27 PM)mp3909 Wrote: Hi,

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

https://docs.python.org/3/tutorial/contr...statements

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


Possibly Related Threads…
Thread Author Replies Views Last Post
  itertools.zip_shortest() fo unequal iterators Skaperen 10 6,728 Dec-27-2019, 12:17 AM
Last Post: Skaperen
  how to join 2 iterators Skaperen 2 2,670 Sep-11-2019, 07:19 PM
Last Post: Skaperen
  iterating over 2 iterators Skaperen 2 2,252 Jun-07-2019, 11:37 PM
Last Post: Skaperen
  2 iterators or generators Skaperen 1 33,146 Jan-04-2018, 07:41 AM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020