Python Forum
how to detect 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 detect a sequence? (/thread-30675.html)



how to detect a sequence? - Skaperen - Oct-31-2020

what is the best way to detect if a given value is a sequence or not? my first thought is to try to slice it under try/except.


RE: how to detect a sequence? - bowlofred - Oct-31-2020

You can use the abstract base class definitions in the collections module to compare against.

>>> import collections.abc
>>> isinstance("ABC", collections.abc.Sequence)
True
>>> isinstance([1, 2, 3], collections.abc.Sequence)
True
>>> isinstance((1, 2, 3), collections.abc.Sequence)
True
>>> isinstance({1, 2, 3}, collections.abc.Sequence)
False
>>> isinstance({'a':1, 'b':2}, collections.abc.Sequence)
False