Skip to Content
Python in a Nutshell
book

Python in a Nutshell

by Alex Martelli
March 2003
Intermediate to advanced
656 pages
39h 30m
English
O'Reilly Media, Inc.
Content preview from Python in a Nutshell

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.

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.
Start your free trial

You might also like

Python in a Nutshell, 3rd Edition

Python in a Nutshell, 3rd Edition

Alex Martelli, Anna Ravenscroft, Steve Holden
Python in a Nutshell, 4th Edition

Python in a Nutshell, 4th Edition

Alex Martelli, Anna Martelli Ravenscroft, Steve Holden, Paul McGuire
Data Wrangling with Python

Data Wrangling with Python

Jacqueline Kazil, Katharine Jarmul

Publisher Resources

ISBN: 0596001886Supplemental ContentCatalog PageErrata