Python Forum
how to test if something is a sequence? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: how to test if something is a sequence? (/thread-42277.html)



how to test if something is a sequence? - Skaperen - Jun-09-2024

how to test if something is a sequence (as opposed to merely a list)?


RE: how to test if something is a sequence? - Gribouillis - Jun-10-2024

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)



RE: how to test if something is a sequence? - Kelly_Doyle - Jun-10-2024

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.


RE: how to test if something is a sequence? - snippsat - Jun-10-2024

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



RE: how to test if something is a sequence? - perfringo - Jun-11-2024

(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. /.../



RE: how to test if something is a sequence? - Skaperen - Jun-11-2024

does that mean i can't use an int to index a mapping? or is an int mutable (i don't think so)?