0

as per the title, how to find list length of sublist that made from list and int. For example, give a list

ListNo=[[6,2,5],[3,10],4,1]

it should return LengthSubList 3,2,1,1.

I make the following code,

LengthSubList=[len(x) for x in ListNo]

But, compiler give the following error

object of type 'int' has no len()

May I know what I do wrong?

Thanks in advance

mpx
  • 3,081
  • 2
  • 26
  • 56

2 Answers2

1

Check if it's a list before you do len():

ListNo = [[6,2,5],[3,10],4,1]

print([len(x) if isinstance(x, list) else 1 for x in ListNo])
# [3, 2, 1, 1]

What you got wrong is you cannot do len(4) and len(1), simply because it would return a TypeError - object of type 'int' has no len().

Austin
  • 25,759
  • 4
  • 25
  • 48
1

Your code will call len(4) and len(1) in your list comprehension which throws the self explanatory error. Try this:

LengthSubList=[len(x) if type(x) == list else 1 for x in ListNo]
Julien
  • 13,986
  • 5
  • 29
  • 53