correct way to detect container type

Peter Otten __peter__ at
Thu Oct 7 11:50:22 CEST 2004

Robin Becker wrote:

> I seem often to allow list/tuple arguments to be a singleton. This leads
> to code of the form
> if type(arg) not in (type(()),type([])): arg = [arg]
> or alternatively
> from type import ListType, TupleType
> _seqTypes = ListType, TupleType
> ......
> if type(arg) not in _seqTypes: ....
> is there a 'best' way to do this?

I prefer 

isinstance(var, (list, tuple))

to the above, but I don't think there is one correct way. Often you don't
want a full-blown container, just an iterable. Then

    it = iter(var)
except TypeError:
    it = iter([var])

may be more appropriate. However, you will end up iterating over the
characters if var is a string, which often has to be guarded against with
an additional isinstance(basestring) test

except TypeError:
    var = [var]
    if isinstance(var, basestring): var = [var]


More information about the Python-list mailing list