Ralph Deint Ralph Deint - 6 months ago 9
Python Question

Python doesn't differentiate len() of list and string?

For example I have this pandas simple data frame:

>> print(file)
Name
0 ['junior','senior']
1 freshgrad


when I tried using :

>> len(file[0])
2


but for the second one

>> len(file[1])
9


But I want the second one to calculate as
1
how to differentiate between these two?


  1. I have tried using
    .join()
    but it still calculate as
    9

  2. I have tried
    list.count
    but I got an error


Answer

You could define your own length function, which uses the type to determine how to calculate the length:

def mylen(data):
    return len(data) if isinstance(data,list) else 1
Comments