Python Iterable vs Sequence

The Sequence and Iterable abstract base classes (can also be used as type annotations) mostly* follow Python’s definition of sequence and iterable. To be specific:

  • Iterable is any object that defines __iter__ or __getitem__.
  • Sequence is any object that defines __getitem__ and __len__. By definition, any sequence is an iterable. The Sequence class also defines other methods such as __contains__, __reversed__ that calls the two required methods.

Some examples:

  • list, tuple, str are the most common sequences.
  • Some built-in iterables are not sequences. For example, reversed returns a reversed object (or list_reverseiterator for lists) that cannot be subscripted.

* Iterable does not exactly conform to Python’s definition of iterables — it only checks if the object defines __iter__, and does not work for objects that’s only iterable via __getitem__ (see this table for details). The gold standard of checking if an object is iterable is using the iter builtin.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)