iter(x) will raise a TypeError if x cannot be iterated on -- but that check "accepts" sets and dictionaries, though it "rejects" other non-sequences such as None and numbers.

On the other hands, strings (which most applications want to consider "single items" rather than sequences) are in fact sequences (so, any test, unless specialcased for strings, is going to confirm that they are). So, such simple checks are often not sufficient.

In Python 2.6 and better, abstract base classes were introduced, and among other powerful features they offer more good, systematic support for such "category checking".

>>> import collections
>>> isinstance([], collections.Sequence)
True
>>> isinstance((), collections.Sequence)
True
>>> isinstance(23, collections.Sequence)
False
>>> isinstance('foo', collections.Sequence)
True
>>> isinstance({}, collections.Sequence)
False
>>> isinstance(set(), collections.Sequence)
False

You'll note strings are still considered "a sequence" (since they are), but at least you get dicts and sets out of the way. If you want to exclude strings from your concept of "being sequences", you could use collections.MutableSequence (but that also excludes tuples, which, like strings, are sequences, but are not mutable), or do it explicitly:

import collections

def issequenceforme(obj):
    if isinstance(obj, basestring):
        return False
    return isinstance(obj, collections.Sequence)

Season to taste, and serve hot!-)

PS: For Python 3, use str instead of basestring, and for Python 3.3+: Abstract Base Classes like Sequence have moved to collections.abc.

Answer from Alex Martelli on Stack Overflow
Top answer
1 of 8
111

iter(x) will raise a TypeError if x cannot be iterated on -- but that check "accepts" sets and dictionaries, though it "rejects" other non-sequences such as None and numbers.

On the other hands, strings (which most applications want to consider "single items" rather than sequences) are in fact sequences (so, any test, unless specialcased for strings, is going to confirm that they are). So, such simple checks are often not sufficient.

In Python 2.6 and better, abstract base classes were introduced, and among other powerful features they offer more good, systematic support for such "category checking".

>>> import collections
>>> isinstance([], collections.Sequence)
True
>>> isinstance((), collections.Sequence)
True
>>> isinstance(23, collections.Sequence)
False
>>> isinstance('foo', collections.Sequence)
True
>>> isinstance({}, collections.Sequence)
False
>>> isinstance(set(), collections.Sequence)
False

You'll note strings are still considered "a sequence" (since they are), but at least you get dicts and sets out of the way. If you want to exclude strings from your concept of "being sequences", you could use collections.MutableSequence (but that also excludes tuples, which, like strings, are sequences, but are not mutable), or do it explicitly:

import collections

def issequenceforme(obj):
    if isinstance(obj, basestring):
        return False
    return isinstance(obj, collections.Sequence)

Season to taste, and serve hot!-)

PS: For Python 3, use str instead of basestring, and for Python 3.3+: Abstract Base Classes like Sequence have moved to collections.abc.

2 of 8
21

For Python 3 and 2.6+, you can check if it's a subclass of collections.Sequence:

>>> import collections
>>> isinstance(myObject, collections.Sequence)
True

In Python 3.7 you must use collections.abc.Sequence (collections.Sequence will be removed in Python 3.8):

>>> import collections.abc
>>> isinstance(myObject, collections.abc.Sequence)
True

However, this won't work for duck-typed sequences which implement __len__() and __getitem__() but do not (as they should) subclass collections.Sequence. But it will work for all the built-in Python sequence types: lists, tuples, strings, etc.

While all sequences are iterables, not all iterables are sequences (for example, sets and dictionaries are iterable but not sequences). Checking hasattr(type(obj), '__iter__') will return True for dictionaries and sets.

🌐
Python Like You Mean It
pythonlikeyoumeanit.com › Module2_EssentialsOfPython › SequenceTypes.html
Sequence Types — Python Like You Mean It
A tuple is very similar to a list, in that it can store a sequence of arbitrary objects (a mix of numbers, strings, lists, other tuples, etc.). Where lists are constructed using square-brackets, tuples use parentheses: # creating a tuple >>> x = (1, "a", 2) # tuple with 3 entries # (3) does not make a tuple with one entry # you must provide a trailing comma in this # instance >>> y = (3,) # a tuple with 1 entry >>> type(x) tuple >>> isinstance(y, tuple) True
Discussions

type hinting - python: isinstance(value, Sequence[Real]) - Stack Overflow
Python's typing module allows containers of specific object types to be described, such as Sequence[numbers.Real]. However, the container interfaces in collections.abc do not accept such parameters... More on stackoverflow.com
🌐 stackoverflow.com
python - How to determine whether an object is a sequence - Stack Overflow
So, in order to create a correct ... collections.Sequence? Does the isinstance function actually check if it subclasses the class, or does it only check to see if it implements the appropriate methods? 2010-11-24T17:34:01.297Z+00:00 ... It checks if the object is an instance of a subclass or of a class that has been registered as a "virtual subclass" (see the abc module for info and further links docs.python.org/libra... More on stackoverflow.com
🌐 stackoverflow.com
better understanding of isinstance(x, Sequence/Mapping/etc.) pattern
Environment data Language Server version: v2020.11.2 OS and version: macOS 10.14.6 Python version 3.6.10 (miniconda) Description I am implementing a recursive function that traverses input up to "l... More on github.com
🌐 github.com
2
November 24, 2020
python - why does isinstance check for abc.Sequence return False for custom classes? - Stack Overflow
I've read in the abc python module docs that a Sequence is something that implements the following: __getitem__, __len__, __contains__, __iter__, __reversed__, index, and count. Yet, when I run the More on stackoverflow.com
🌐 stackoverflow.com
🌐
Real Python
realpython.com › what-does-isinstance-do-in-python
What Does isinstance() Do in Python? – Real Python
October 21, 2025 - >>> calculate_area("5", "3") Traceback ... File "<python-input-5>", line 2, in calculate_area return length * breadth ~~~~~~~^~~~~~~~~ TypeError: can't multiply sequence by non-int of type 'str' The multiplication operator can’t cope with two strings, so the code crashes. This is where you could use isinstance() to warn ...
🌐
W3Schools
w3schools.com › python › ref_func_isinstance.asp
Python isinstance() Function
Python Examples Python Compiler ... Q&A Python Training ... The isinstance() function returns True if the specified object is of the specified type, otherwise False....
🌐
CodeCut
codecut.ai › home › simplify multiple type checks in python: tuples and abstract base classes
Simplify Multiple Type Checks in Python: Tuples and Abstract Base Classes | CodeCut
April 13, 2026 - def is_sequence(obj): return isinstance(obj, (list, tuple, str)) print(is_sequence([1, 2, 3])) # True print(is_sequence((1, 2, 3))) # True print(is_sequence("123")) # True print(is_sequence(123)) # False · For broader type checking, use Python’s abstract base classes:
🌐
LabEx
labex.io › tutorials › python-how-to-validate-sequence-type-418550
How to validate sequence type | LabEx
Type validation is a critical process in Python programming to ensure data integrity and prevent runtime errors. This section explores various methods to validate sequence types. def validate_sequence(data): ## Check if data is a sequence type if isinstance(data, (list, tuple, str, range)): print("Valid sequence type") else: print("Invalid sequence type") ## Examples validate_sequence([1, 2, 3]) ## Valid validate_sequence("Hello") ## Valid validate_sequence((1, 2, 3)) ## Valid validate_sequence(42) ## Invalid
🌐
Stack Overflow
stackoverflow.com › questions › 41086266 › python-isinstancevalue-sequencereal
type hinting - python: isinstance(value, Sequence[Real]) - Stack Overflow
Python's typing module allows containers of specific object types to be described, such as Sequence[numbers.Real]. However, the container interfaces in collections.abc do not accept such parameters, so I can only check isinstance(value, abc.Sequence).
Find elsewhere
🌐
PYnative
pynative.com › home › python › python isinstance() function explained with examples
Python isinstance() function explained with examples
June 29, 2021 - The isinstance() function works on the principle of the is-a relationship. The concept of an is-a relationship is based on class inheritance. The instance() returns True if the classinfo argument of the instance() is the object’s class’s parent class. To demonstrate this, I have created two classes, Developer and PythonDeveoper.
🌐
Programiz
programiz.com › python-programming › methods › built-in › isinstance
Python isinstance()
result = isinstance(numbers, list) print(numbers,'instance of list?', result) result = isinstance(numbers, dict) print(numbers,'instance of dict?', result) result = isinstance(numbers, (dict, list)) print(numbers,'instance of dict or list?', result) number = 5
🌐
Python Forum
python-forum.io › thread-42277.html
how to test if something is a sequence?
how to test if something is a sequence (as opposed to merely a list)?
🌐
Python
docs.python.org › 3 › builtins › functions.html
Built-in Functions — Python 3.14.7 documentation
Rather than being a function, tuple is actually an immutable sequence type, as documented in Tuples and Sequence Types — list, tuple, range. ... With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__. The isinstance() built-in function is recommended for testing the type of an object, because it takes subclasses into account.
🌐
Python Reference
python-reference.readthedocs.io › en › latest › docs › functions › isinstance.html
isinstance — Python Reference (The Right Way) 0.1 documentation
>>> isinstance(u'foo', (basestring, str, unicode)) True >>> isinstance(u'foo', (basestring, str)) True >>> isinstance(u'foo', (basestring)) True >>> isinstance(u'foo', (str)) False
🌐
CodeGenes
codegenes.net › blog › what-does-isinstance-do-in-python
Understanding `isinstance()` in Python — codegenes.net
Python's abc (Abstract Base Classes) module provides a way to define abstract interfaces. You can use isinstance() with these abstract base classes to check if an object conforms to a certain interface. from collections.abc import Sequence my_list = [1, 2, 3] print(isinstance(my_list, Sequence)) # Output: True my_set = {1, 2, 3} print(isinstance(my_set, Sequence)) # Output: False
🌐
Mun
engr.mun.ca › ~theo › Courses › AlgCoCo › recursionWonderland › Sequence-Length.html
Sequence-Length
""" assert isinstance(s, tuple) return (x,) + s def first( s ) : """Pre: s is is a nonempty sequence represented by a tuple Post: result the first item of the sequence """ assert isinstance(s, tuple) and s != () return s[0] ; def rest( s ) : """Pre: s is is a nonempty sequence represented by a tuple Post: result the first item of the sequence """ assert isinstance(s, tuple) and s != () fst, *rst = s return tuple(rst); def decons( s ) : """Pre: s is is a nonempty sequence represented by a tuple Post: result is a pair consisting of the first items of s and a tuple of the rest of the items """ assert isinstance(s, tuple) and s != () fst, *rst = s return fst, tuple(rst)
🌐
YouTube
youtube.com › watch
Understanding isinstance(): A Friendly Tutorial in Python - YouTube
Check out this video to learn more about Python's isinstance method. The isinstance() method in Python is a built-in function that is used to check whether a...
Published: January 11, 2024
🌐
GitHub
github.com › microsoft › pylance-release › issues › 645
better understanding of isinstance(x, Sequence/Mapping/etc.) pattern · Issue #645 · microsoft/pylance-release
November 24, 2020 - import typing def f(x): if isinstance(x, typing.Sequence): return type(x)(f(item) for item in x) # PROBLEM HERE else: return 2 * x
Author: microsoft
Top answer
1 of 16
330

In python 2 only (not python 3):

assert not isinstance(lst, basestring)

Is actually what you want, otherwise you'll miss out on a lot of things which act like lists, but aren't subclasses of list or tuple.

2 of 16
175

Remember that in Python we want to use "duck typing". So, anything that acts like a list can be treated as a list. So, don't check for the type of a list, just see if it acts like a list.

But strings act like a list too, and often that is not what we want. There are times when it is even a problem! So, check explicitly for a string, but then use duck typing.

Here is a function I wrote for fun. It is a special version of repr() that prints any sequence in angle brackets ('<', '>').

def srepr(arg):
    if isinstance(arg, basestring): # Python 3: isinstance(arg, str)
        return repr(arg)
    try:
        return '<' + ", ".join(srepr(x) for x in arg) + '>'
    except TypeError: # catch when for loop fails
        return repr(arg) # not a sequence so just return repr

This is clean and elegant, overall. But what's that isinstance() check doing there? That's kind of a hack. But it is essential.

This function calls itself recursively on anything that acts like a list. If we didn't handle the string specially, then it would be treated like a list, and split up one character at a time. But then the recursive call would try to treat each character as a list -- and it would work! Even a one-character string works as a list! The function would keep on calling itself recursively until stack overflow.

Functions like this one, that depend on each recursive call breaking down the work to be done, have to special-case strings--because you can't break down a string below the level of a one-character string, and even a one-character string acts like a list.

Note: the try/except is the cleanest way to express our intentions. But if this code were somehow time-critical, we might want to replace it with some sort of test to see if arg is a sequence. Rather than testing the type, we should probably test behaviors. If it has a .strip() method, it's a string, so don't consider it a sequence; otherwise, if it is indexable or iterable, it's a sequence:

def is_sequence(arg):
    return (not hasattr(arg, "strip") and
            hasattr(arg, "__getitem__") or
            hasattr(arg, "__iter__"))

def srepr(arg):
    if is_sequence(arg):
        return '<' + ", ".join(srepr(x) for x in arg) + '>'
    return repr(arg)

EDIT: I originally wrote the above with a check for __getslice__() but I noticed that in the collections module documentation, the interesting method is __getitem__(); this makes sense, that's how you index an object. That seems more fundamental than __getslice__() so I changed the above.