Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator (iter()) function in Python.

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?

ADDED

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
like image 300
prosseek Avatar asked Oct 15 '10 01:10

prosseek


People also ask

What does ITER () do in Python?

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.

How do I return an iterator in Python?

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.


2 Answers

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
like image 60
Glenn Maynard Avatar answered Sep 28 '22 09:09

Glenn Maynard


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.

like image 27
Winston Ewert Avatar answered Sep 28 '22 10:09

Winston Ewert