What is the difference between type-hinting a variable as an Iterable versus a Sequence?
May 8
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]):
...
1 answer
Accepted answer · original discussion
May 8
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. TheSequenceclass also defines other methods such as__contains__,__reversed__that calls the two required methods.
Some examples:
list,tuple,strare the most common sequences.- Some built-in iterables are not sequences. For example,
reversedreturns areversedobject (orlist_reverseiteratorfor 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.
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
Jun 29