Search code examples
pythonlistinfodescribe

What is the analogous of the describe() or info() methods for a List in Python?


Given a list I would like a way to explore its contents.

len() will give me the number of items in the list but how I could go further than that? E.g. get information about the classes of the objects contained in the list and their size?

This is a rather general question. If you feel I should produce some concrete example let me know.


Solution

  • If you want to know the available attributes and methods of a list, you can print the online help:

    help(list)
    

    If you want the documentation of a method, you can do, for instance:

    help(list.append)
    

    If you want the number of items you can use Len function:

    l = [True, None, "Hi", 5, 3.14]
    print("Length of the list is {0}".format(len(l)))
    # -> Length of the list is 5
    

    If you want the memory size of your list reference, you can try sys.getsizeof function:

    import sys
    
    print(sys.getsizeof(l))
    # -> 104
    

    For the memory size of the items, just sum the individual sizes:

    print(sum(sys.getsizeof(i) for i in l))
    # -> 147
    

    To list the type of each item, use the type function:

    for item in l:
        print(type(item))
    

    You get:

    <class 'bool'>
    <class 'NoneType'>
    <class 'str'>
    <class 'int'>
    <class 'float'>