Search code examples
pythonpython-3.xlistvariable-length

Can I quickly get the minimum length of the most inner sub-lists within a list in python?


This shows how to get the minimum length of first-level inner lists.

How can I return 4 for this list b=[[1,0,1,2,1,1,1,3111111,[1,1,6,7]],[31,1,4,51,1,1,1],[1,1,6,7,8]] as [1,1,6,7] only has 4 elements.

I can run a for-loop to get it. But can it be simpler?

I mean "the length of the shortest list that is at the same depth as the deepest list".


Solution

  • v1, minimum length at any depth:

    >>> b = [[1,0,1,2,1,1,1,3111111,[1,1,6,7]],[31,1,4,51,1,1,1],[1,1,6,7,8]]
    >>> def lists_in(L):
    ...     for element in L:
    ...         if isinstance(element, list):
    ...             yield element
    ...             yield from lists_in(element)
    ...             
    >>> min(lists_in(b), key=len)
    [1, 1, 6, 7]
    >>> len(min(lists_in(b), key=len))
    4
    

    v2, with new requirement "the length of the shortest list that is at the same depth as the deepest list":

    >>> def depths_and_lengths(L, depth=0):
    ...     for element in L:
    ...         if isinstance(element, list):
    ...             yield (depth, len(element))
    ...             yield from depths_and_lengths(element, depth-1)
    ...             
    ...             
    >>> min(depths_and_lengths(b))[1]
    4
    >>> min(depths_and_lengths([[[1, 2]]]))[1]    # Stefan Pochmann example
    2