Home > OS >  Python Iterable vs Sequence
Python Iterable vs Sequence

Time:05-09

I don't understand the difference when hinting Iterable and Sequence.

What is the main difference between those two and when to use which?

I think set is an Iterable but not Sequence, are there any built-in data type that is Sequence but not Iterable?

def foo(baz: Sequence[float]):
  ...

# What is the difference?
def bar(baz: Iterable[float]):
  ...

CodePudding user response:

The Sequence and Iterable abstract base classes (can also be used as type annotations) 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 iterators are not sequences. For example, reversed returns a reversed iterator object (or list_reverseiterator for lists) that cannot be subscripted.
  • Related