[Tutor] Tutor Digest, Vol 102, Issue 98

eryksun eryksun at gmail.com
Sat Sep 1 03:46:33 CEST 2012


On Fri, Aug 31, 2012 at 8:20 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> Sequence
>   The generalisation of lists, tuples and strings. Any object that has
>   a known length where individual items can be retrieved with the
>   __getitem__ method called sequentially: obj[0], obj[1], obj[2], ...

To expand on this, any object that has a __getitem__ method can be
iterated over until it raises an IndexError, not just object's that
have an __iter__ method, and __len__ is not a factor. For example:

    class Test(object):
        def __getitem__(self, n):
            if n > 4:
                raise IndexError
            return 'test'

    >>> list(Test())
    ['test', 'test', 'test', 'test', 'test']


More information about the Tutor mailing list