Python Forum

Full Version: how to test if something is a sequence?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
how to test if something is a sequence (as opposed to merely a list)?
Use perhaps collections.abc.Iterable
isinstance(obj, Iterable)
Documentation Wrote:The only reliable way to determine whether an object is iterable is to call iter(obj)
To test if something is a sequence rather than just a list, you can check if it has a specific order or arrangement that follows a pattern or progression. Sequences typically exhibit a logical or numerical progression, whereas lists may not necessarily have a defined order. It's about identifying the underlying structure and patterns within the data.
There is from collections.abc import Sequence.
In Python, a sequence is an abstract data type that represents an ordered collection of items.
from collections.abc import Sequence

def is_sequence(obj):
    return isinstance(obj, Sequence)
>>> example_list = [1, 2, 3]
>>> is_sequence(example_list)
True
>>> example_string = "123"
>>> is_sequence(example_string)
True
Dictionaries and sets return False because they are not considered sequences in the context of the Sequence abstract base class.
>>> example_dict = {1: "a", 2: "b", 3: "c"}
>>> is_sequence(example_dict)
False
>>> example_set = {1, 2, 3}
>>> is_sequence(example_set)
False
(Jun-09-2024, 11:54 PM)Skaperen Wrote: [ -> ]how to test if something is a sequence (as opposed to merely a list)?

List is sequence so there is no opposition.

Python documentation > Glossary > sequence:

Quote:sequence
An iterable which supports efficient element access using integer indices via the __getitem__() special method and defines a __len__() method that returns the length of the sequence. Some built-in sequence types are list, str, tuple, and bytes. Note that dict also supports __getitem__() and __len__(), but is considered a mapping rather than a sequence because the lookups use arbitrary immutable keys rather than integers. /.../
does that mean i can't use an int to index a mapping? or is an int mutable (i don't think so)?