Sometimes Python confuses me:
>>> range(2**128-1, 0, -1)
range(340282366920938463463374607431768211455, 0, -1)
>>> next(_)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'range' object is not an iterator

BUT, this is because of a difference between an iterable object and an iterator object.

for takes an iterable, and creates an "iterator" from that iterable, that is, calling iter on it.

given:
for i in j:
<body>

It can be rewritten as:
_iterobj = iter(j)
while True:
try:
i = next(_iterobj)
except StopIteration:
break
else:
<body>

Follow

@encthenet Interesting! Java draws the same distinction, but the Iterator has a separate hasNext() method rather than throwing an exception when the Iterator is empty.

Sign in to participate in the conversation
CleverLibre Social

CleverLibre Social is an inclusive social instance for open discussion, learning, and community.
All cultures welcome.
Hate speech and harassment strictly forbidden.