Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the differences between container.__iter__() and iterator.__iter__()?

Tags:

python

I am poor in python so don't beat me please.

>>> a = ['a', 'b', 'c']
>>> a.__iter__()
<listiterator object at 0x03531750>
>>> a.__iter__().__iter__()
<listiterator object at 0x03531690>

I see that both of listiterator objects lives in other places (true that 0x03531750 is like place?). I need to know that both of these objects are the same, but lives in other places or they are different?

like image 285
Cadilac Avatar asked Dec 28 '25 15:12

Cadilac


1 Answers

An iterator has an __iter__() method so that you can call iter() on it to get an iterator for it, even though it already is one. Makes it easier to write things that use iterators if you don't have to be constantly checking whether something is already an iterator or not.

So you're getting an iterator for the list, and then getting an iterator for that iterator. An iterator for an iterator is the original iterator (Python doesn't create a second iterator, there's no point).

OK, good so far.

Iterators are objects and, like all objects, have a lifecycle. They are created when you call __iter__() (or iter()) on the object and destroyed when there are no longer any references to them. In your example, you do a.__iter__(), which creates the list iterator. Then, since you don't keep a reference to the it anywhere, this iterator is destroyed more or less immediately (though this is an implementation detail). So your next command, a.__iter__().__iter__() creates a new iterator for the list (only one, because the iterator of an iterator is the same iterator) -- it does not reuse the iterator you made in the previous command, because that iterator is gone. This is why the objects have different IDs; they are in fact different objects.

You will see that a.__iter__() and a.__iter__().__iter__() are the same object if you keep a reference to the former. Try this:

a = ['a', 'b', 'c']
i = iter(a)    # a.__iter__()
j = iter(i)    # i.__iter__() which is a.__iter__().__iter__()
print i is j   # True, they're the same object
like image 56
kindall Avatar answered Dec 31 '25 05:12

kindall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!