Mar-16-2018, 04:27 PM
Hi,
Quick question, is "for" an iterator in python?
Quick question, is "for" an iterator in python?
Iterators
|
Mar-16-2018, 04:27 PM
Hi,
Quick question, is "for" an iterator in python?
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'"
Mar-16-2018, 05:40 PM
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
Mar-16-2018, 09:42 PM
(Mar-16-2018, 04:27 PM)mp3909 Wrote: Hi, https://docs.python.org/3/tutorial/contr...statements No, it's not an iterator. It's a construct that iterates over an iterator. |
|
Possibly Related Threads… | |||||
Thread | Author | Replies | Views | Last Post | |
itertools.zip_shortest() fo unequal iterators | Skaperen | 10 | 9,495 |
Dec-27-2019, 12:17 AM Last Post: Skaperen |
|
how to join 2 iterators | Skaperen | 2 | 3,571 |
Sep-11-2019, 07:19 PM Last Post: Skaperen |
|
iterating over 2 iterators | Skaperen | 2 | 3,088 |
Jun-07-2019, 11:37 PM Last Post: Skaperen |
|
2 iterators or generators | Skaperen | 1 | 42,956 |
Jan-04-2018, 07:41 AM Last Post: Gribouillis |