Object is enumerable but not indexable?

Python only allows these things if the class has methods for them:

  • __getitem__ is required for the [] syntax.
  • __iter__ and __next__1 are required to iterate.

Any class can define one without defining the other. __getattr__ is usually not defined if it would be inefficient.


1__next__ is required on the class returned by __iter__.


This is a result of foo being iterable, but not having a __getitem__ function. You can use itertools.isslice to get the nth element of an iterable like so

import itertools

def nth(iterable, n, default=None):
    "Returns the nth item or a default value"
    return next(itertools.islice(iterable, n, None), default)