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 Sequence
Sequence
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:
Sequence
is 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,
Sequence
can be parameterized with other types, such asSequence[str]
for a sequence of strings. -
Subtyping: A
Sequence
is more abstract than specific sequence types likelist
ortuple
. This means alist
ortuple
can be used where aSequence
is 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)