Junior — Middle
What is the difference between Sequence and Iterable types in Python?
sobes.tech AI
Answer from AI
In Python, an Iterable is any object that can be iterated over, i.e., you can obtain an iterator from it using the iter() function. Examples include lists, strings, dictionaries, and files.
A Sequence is a subtype of iterable that supports ordered access to elements by index and usually has a fixed sequence of elements. Sequences implement __getitem__ and __len__, allowing index access and length queries.
In other words:
- All Sequence objects are Iterable.
- Not all Iterables are Sequences (e.g., sets and generators are iterable but not sequences).
Example:
from collections.abc import Iterable, Sequence
print(issubclass(list, Iterable)) # True
print(issubclass(list, Sequence)) # True
print(issubclass(set, Iterable)) # True
print(issubclass(set, Sequence)) # False
Thus, Sequence is an ordered and indexable iterable.