Search code examples
pythoncompiler-errorsvariable-length

Find list length of sublist that made from list and int


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


Solution

  • 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().