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 += 1
See 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 item
As 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.
Get Python in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.