Iterator instances not independent
Francis Belliveau via Tutor <[email protected]> Sun, 7 Dec 2025 16:41:00 -0500
| Newsgroups | gmane.comp.python.tutor |
|---|---|
| Message-ID | <[email protected]> |
Hello all.
I created a SequenceInt class for iteration but different instances do not seem independent. The code looks like:
class SequenceInt:
def __init__(self, last=10):
self.val = 0
self.LAST = last
def __iter__(self):
self.val = 0
return self
def __next__(self):
if (self.hasNext()):
self.val += 1
else:
raise StopIteration
return self.val
def __len__(self):
return self.LAST - self.val
def hasNext(self):
return bool(len(self))
The main body of the test application looks like:
seqA = SequenceInt()
seqB = SequenceInt(5)
itB = iter(seqB)
itA = iter(seqA)
for x in seqA:
if (seqB.hasNext()):
bStr = str(next(itB))
else:
bStr = "done"
print("A =", next(itA), "B =", bStr)
The output looks like:
A = 2 B = 1
A = 4 B = 2
A = 6 B = 3
A = 8 B = 4
A = 10 B = 5
The question is why does A increment by 2?
Aren't the two iterators independent of each other?
This doesn't seem too complex to me.
Python version is: 3.9.6 (default, Oct 17 2025, 17:15:53) [Clang 17.0.0 (clang-1700.4.4.1)] on Mac OS 26.1
Looking forward to any help understanding why this is happening.
Fran
_______________________________________________
Tutor maillist - To unsubscribe send an email to [email protected]
To unsubscribe or change subscription options:
%(web_page_url)slistinfo/%(_internal_name)s