16

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
1
  • 2
    Both your examples work for me. Python 2.6 here Commented Oct 15, 2010 at 2:09

2 Answers 2

17

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
Sign up to request clarification or add additional context in comments.

2 Comments

When iter(x) and x gives the same result, what's for the iter()? Thanks for finding the typo.
iter converts an object to an iterator (that is, it returns the iterator for an object). When the object is already an iterator, this does nothing and __iter__ simply returns itself. for i in x is actually calling iter for you; since that's unnecessary (it's already an iterator), the iterator's __iter__ call returns itself.
8

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.