Distinguishing Strings from Sequences in Python

Determining Whether a Value Is a String or a Sequenec

In Python, distinguishing between string and sequence types (e.g., lists, tuples, or other iterable containers) requires careful type inspection—especially since strings are technical sequences themselves but often need special handling.

Core Strategy

Use isinstance() with precise type checks. Avoid relying solely on duck typing for this distintcion, as strings satisfy many sequence protocols (e.g., __iter__, __len__) but behave differently in most domain logic.

Check for String Type

To confirm a value is specifically a string (and not just any sequence), test against str:

def identify_type(value):
    if isinstance(value, str):
        return "string"
    elif isinstance(value, (list, tuple, set, frozenset, bytes, bytearray)):
        return "sequence-like"
    else:
        return "other"

# Examples
print(identify_type("hello"))     # → "string"
print(identify_type([1, 2, 3]))   # → "sequence-like"
print(identify_type((4, 5)))      # → "sequence-like"

This function explicitly prioritizes str before broader sequence types, ensuring correct categorization even when both conditions could superficially apply.

Extended Sequence Detection

For more robust detection—including user-defined sequence-like classes—consider checking abstract base classes from collections.abc while excluding strings:

from collections.abc import Sequence

def classify(value):
    if isinstance(value, str):
        return "text"
    elif isinstance(value, Sequence):
        return "structured_sequence"
    else:
        return "non_sequence"

# Usage
print(classify("abc"))          # → "text"
print(classify(range(3)))       # → "structured_sequence"
print(classify({"a": 1}))       # → "non_sequence"

Note that range, deque, and custom classes inheriting from Sequence will be classified accordingly—while str remains excluded due to the early guard clause.

Tags: python type-checking isinstance strings Sequences

Posted on Sun, 11 Oct 2026 16:47:36 +0000 by therealairness