Ralph Deint Ralph Deint - 1 year ago 63
Python Question

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

For example I have this pandas simple data frame:

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

when I tried using :

>> len(file[0])

but for the second one

>> len(file[1])

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

  1. I have tried using
    but it still calculate as

  2. I have tried
    but I got an error

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download