The Sequence type in Python's typing module is used for type hinting in situations where an ordered collection of items is expected. It's a step towards more precise and readable code, especially when dealing with functions or methods that operate on sequences like lists, tuples, or strings.
To use Sequence, you must first import it:
from typing import SequenceSequence serves as a type hint to indicate that a function parameter, variable, or return type should be a sequence.
Example:
def process_items(items: Sequence[int]) -> None:
# process the sequence of items here
...-
Immutability:
Sequenceis typically used to represent immutable sequences. While you can iterate over and access elements in aSequence, modifying it is not allowed. -
Generics: As a generic type,
Sequencecan be parameterized with other types, such asSequence[str]for a sequence of strings. -
Subtyping: A
Sequenceis more abstract than specific sequence types likelistortuple. This means alistortuplecan be used where aSequenceis expected, but not vice versa. -
Common Methods: Methods such as
__getitem__,__len__,__contains__, index, and count are part of the Sequence interface.
def sum_sequence(numbers: Sequence[float]) -> float:
return sum(numbers)def concatenate_strings(strings: Sequence[str]) -> str:
return ''.join(strings)