Anna
Anna

Reputation: 23

How can I count the depth in a list of lists?

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

Answers (2)

Red
Red

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:

  1. First check if object passed into the recursive function is of type list:
def max_level(lst):
    return isinstance(lst, list)
  1. If so, proceed to add up the Trues in the list:
and max(map(max_level, lst)) + 1

where the max(map(max_level, lst)) returns the current amount of Trues, 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

cdlane
cdlane

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

Related Questions