Reputation: 23
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
Upvotes: 1
Views: 622
Reputation: 27567
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:
list
:def max_level(lst):
return isinstance(lst, list)
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
Upvotes: 3
Reputation: 41872
I want to search through a list that is empty as well
Give this a try:
def max_level(thing):
return 1 + (max(map(max_level, thing)) if thing else 0) if isinstance(thing, list) else 0
I've reworked @AnnZen's initial solution to add an extra check for empty lists and also to not mix booleans and integers.
Upvotes: 0