The way you take a length of anything for which that makes sense (a list, dictionary, tuple, string, ...) is to call len
on it.
l = [1,2,3,4]
s = 'abcde'
len(l) #returns 4
len(s) #returns 5
The reason for the "strange" syntax is that internally python translates len(object)
into object.__len__()
. This applies to any object. So, if you are defining some class and it makes sense for it to have a length, just define a __len__()
method on it and then one can call len
on those instances.