For dictionary, I can use iter()
for iterating over keys of the dictionary.
y = {"x":10, "y":20}
for val in iter(y):
print val
When I have the iterator as follows,
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def next(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
Why can't I use it this way
x = Counter(3,8)
for i in x:
print x
nor
x = Counter(3,8)
for i in iter(x):
print x
but this way?
for c in Counter(3, 8):
print c
What's the usage of iter()
function?
I guess this can be one of the ways of how iter()
is used.
class Counter:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def next(self):
if self.current > self.high:
raise StopIteration
else:
self.current += 1
return self.current - 1
class Hello:
def __iter__(self):
return Counter(10,20)
x = iter(Hello())
for i in x:
print i
python iter() method returns the iterator object, it is used to convert an iterable to the iterator. Parameters : obj : Object which has to be converted to iterable ( usually an iterator ). sentinel : value used to represent end of sequence.
Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__() and __next__() . The __iter__ returns the iterator object and is implicitly called at the start of loops. The __next__() method returns the next value and is implicitly called at each loop increment.
All of these work fine, except for a typo--you probably mean:
x = Counter(3,8)
for i in x:
print i
rather than
x = Counter(3,8)
for i in x:
print x
I think your actual problem is that you print x
when you mean to print i
iter()
is used to obtain an iterator over a given object. If you have an __iter__
method that defines what iter will actually do. In your case you can only iterate over the counter once. If you defined __iter__
to return a new object it would make it so that you could iterate as many times as you wanted. In your case, Counter is already an iterator which is why it makes sense to return itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With