'How to determine the number of layers of lists a list has?
Given that a list can be within a list, and list can be within a list within a list, and so forth, I'd like to know the number of lists that exist within another list within a list.
For example,
l1 = [1] #1 is within 1 list
l2 = [[1]] #1 is within 2 lists
l3 = [[[1]]] #1 is within 3 lists
l4 = [[[[1]]]] #1 is within 4 list
I'd like to know that l1 is 1 list deep, l2 is 2 lists deep, l3 is 3 lists deep and so forth.
Solution 1:[1]
Assuming it's a simple structure of nested lists like your examples, you can simply count the number opening brackets :)
l4 = [[[[1]]]]
print len(str(l4)) - len(str(l4).replace('[', '')) # 4
Solution 2:[2]
You have to dig into every sublist.
def depth(lst):
if not isinstance(lst, list):
return 0
else:
return 1 + max(depth(sublist) for sublist in lst)
Solution 3:[3]
I hope this helps,
def depth (givenList):
for i in givenList:
if not isinstance(i,list):
return 1
else:
return depth(i)+1
print depth(l1)
Solution 4:[4]
Using len(numpy.array(list))could work
print(len(numpy.array(l2))) # return 2
print(len(numpy.array(l3))) # return 3
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nir Alfasi |
| Solution 2 | |
| Solution 3 | Sujay Narayanan |
| Solution 4 |
