Search code examples
pythontypestuplesinstanceof

Tuple type content python


Can I somehow see the types and size of the contents of a tuple? I'd like the output something like:

(str, list, int) or whatever is possible (just printing them is hard as there are nested lists)

x = someSecretTupleFromSomewhereElse
print type(x)

<(type 'tuple')>

Solution

  • >>> data = ('ab', [1, 2, 3], 101)
    >>> map(type, data)
    [<type 'str'>, <type 'list'>, <type 'int'>]
    

    To also display the length you can do this, for items that aren't sequences I'll just display None.

    >>> import collections
    >>> [(type(el), len(el) if isinstance(el, collections.Sequence) else None)
         for el in data]
    [(<type 'str'>, 2), (<type 'list'>, 3), (<type 'int'>, None)]