Search code examples
python-3.xlistfunctionisinstance

How to explain in layman's terms for this function (function, list, in and isinstance)?


I came across this function:

 def count_list(l):          
      count = 0          
      for e in l:               
           if isinstance(e, list):                    
                count = count + 1 + count_list(e)                    
      return count

I couldn't understand it especially the for e in 1 and isinstance(e, list), wonder if any pro can explain? Just started learning function, list, in and isinstance


Solution

  • Let's read it:

    # define the method count_list that take one argument l (lower L)
    def count_list(l):
        # define count to be a int with value 0
        count = 0
        # for each item e in l (we supose that l can be itered)
        for e in l:
            # if e is a list
            if isinstance(e, list):
                # add one to count and the result of count_list called on e (recursive call)
                count = count + 1 + count_list(e)                    
        return count
    

    Remarks:

    • If e is not a list count doesn't change. This method increment count by one only when a list is found inside l.
    • It also increment by the number of list in that list in a list.
    • Finally it returns the number of nested list in l. For each list it meet, it add 1+number of list in that list using recursive calls.

    Example:

    Here a representation of the content of l:

    • Element
    • ListA
      • Element
      • Element
      • ListB
        • Element
        • Element
      • ListC
        • Element
    • Element

    What happen when we call count_list(l):

    • count_list is called with the parameter l (call 1).
    • The element of l are iterated.
    • The element ListA is a list. count (in call 1) is incremented by 1 and the result of the call to count_list with the parameter ListA.
    • count_list is called with the parameter ListA (call 2).
      • The element of ListA are iterated.
      • The element ListB is a list. count (in call 2) is incremented by 1 and the result of the call to count_list with the parameter ListB.
        • count_list is called with the parameter ListB (call 3).
        • The element of ListB are iterated.
        • No list are found 0 is returned (call 3)
      • count (in call 2) value is the result of 0+1+0. It's 1.
      • The element ListC is a list. count (in call 2) is incremented by 1 and the result of the call to count_list with the parameter ListC.
        • count_list is called with the parameter ListC (call 4).
        • The element of ListC are iterated.
        • No list are found 0 is returned (call 4)
      • count (in call 2) value is the result of 1+1+0. It's 2.
      • There is no list left in ListA.
      • 2 is returned (call 2)
    • count (in call 1) value is the result of 0+1+2. It's 3.
    • There is no list left in l.
    • 3 is returned (call 1)