Python find size of each sublist in a list

234 views Asked by At

I have a big list of floats and integers as given below. I want to find the length of each sublist by neglecting empty or single elements.

big_list = [[137.83,81.80,198.56],0.0,[200.37,151.55,165.26, 211.84],
 0.0,[1,2,3],4,[5,6,0,5,7,8],0,[2,1,4,5],[9,1,-2]]

My present code:

list_len = []
for i in big_list: 
     list_len.append(len(i))

Present output:

TypeError: object of type 'numpy.float64' has no len() 

Expected output:

list_len = [3,4,3,6,4,3] # list_len should neglect elements like 0, 4 in big_list. 
5

There are 5 answers

0
Gulzar On BEST ANSWER
res = [len(l) for l in big_list if isinstance(l, list) and len(l)> 0]
2
marcos On

Use list comprehension with list type checking like this:

big_list = [[137.83,81.80,198.56],0.0,[200.37,151.55,165.26, 211.84],
 0.0,[1,2,3],4,[5,6,0,5,7,8],0,[2,1,4,5],[9,1,-2]]

lengths = [
    len(sub_list) for sub_list in big_list if isinstance(sub_list, list)
]
print(lengths)

>>> [3, 4, 3, 6, 4, 3]
0
Grigory Feldman On
list(map(len, filter(lambda x: isinstance(x, list), big_list)))
1
Christian Fonseca On

you can use compressed list with if-else statements:

list_len = [len(x) for x in big_list if isinstance(x,list)]
0
Andrea On

I would go for:

big_list = [(137.83,81.80,198.56),0.0,np.array([200.37,151.55,165.26, 211.84]),
 0.0,[1,2,3],4,[5,6,0,5,7,8],0,[2,1,4,5],[9,1,-2]]

list_len = [len(x) for x in big_list if hasattr(x, '__len__') and len(x)>0]

which works with numpy arrays and tuple as well