Name
iter
Synopsis
iter(obj)iter(func,sentinel)
Creates and returns an iterator: an object with a
next method that you can call repeatedly to get
one item at a time (see Section 4.9.3.1
in Chapter 4). When called with one argument,
iter(
obj
)
normally returns obj
.__iter__( ). When obj is a sequence
without a special method __iter__,
iter(
obj
)
is equivalent to the following simple generator:
def iterSequence(obj):
i = 0
while 1:
try: yield obj[i]
except IndexError: raise StopIteration
i += 1See also Section 4.10.8 in Chapter 4 and __iter__ in Chapter 5.
When called with two arguments, the first argument must be callable
without arguments, and
iter(
func,sentinel
)
is equivalent to the following simple generator:
def iterSentinel(func, sentinel):
while 1:
item = func( )
if item = = sentinel: raise StopIteration
yield itemAs discussed in Chapter 4, the statement
for
x
in
obj is equivalent to
for
x
in
iter(
obj
).
iter is idempotent. In other
words, when x is an iterator,
iter(
x
)
is x, as long as
x supplies an __iter__ method whose body is just return
self, as an iterator should.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access