I want to count the depth in a list of lists, so not the amount of elements but the maximum depth one list can have.
This is my function:
def max_level(lst): print(max_level([1, [[[2, 3]]], [[3]]])))
should return 4
Advertisement
Answer
You can try:
def max_level(lst): return isinstance(lst, list) and max(map(max_level, lst)) + 1 print(max_level([1, [[[2, 3]]], [[3]]]))
Output:
4
Explanation:
- First check if object passed into the recursive function is of type
list
:
def max_level(lst): return isinstance(lst, list)
- If so, proceed to add up the
True
s in the list:
and max(map(max_level, lst)) + 1
where the max(map(max_level, lst))
returns the current amount of True
s, and the + 1
is to add one more.
If there can be empty lists, you can replace lst
with lst or [0]
, where the or
will tell python to use the list on the left side of it if its not empty, else use the [0]
:
def max_level(lst): return isinstance(lst, list) and max(map(max_level, lst or [0])) + 1 print(max_level([1, [], [[]]]))
Output:
3
Addressing @cdlane’s comment, if you don’t want to mix boolean values with integer values, you can add an int()
wrapper to the isinstance()
call:
def max_level(lst): return int(isinstance(lst, list)) and max(map(max_level, lst or [0])) + 1