2/17/2023

How to Get the Shape of a List of Lists in Python

refer to code:


...

def get_shape(l):
if isinstance(l, list):
return [len(l)] + get_shape(l[0])
else:
return []

l = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
print(get_shape(l)) # Output: [3, 3]

l = [[1, [2, 3]], [4, [5, [6, [7]]]]]
print(get_shape(l)) # Output: [2, 2, 2, 1]

...


Thank you.

πŸ™‡πŸ»‍♂️

www.marearts.com