In python is this the only way to get the number of elements:
arr.__len__()
If so, why the strange syntax?
In python is this the only way to get the number of elements:
arr.__len__()
If so, why the strange syntax?
mylist = [1,2,3,4,5]
len(mylist)
The same works for tuples:
mytuple = (1,2,3,4,5)
len(mytuple)
It was intentionally done this way so that lists, tuples and other container types didn't all need to explicitly implement a public .length()
method, instead you can just check the len()
of anything that implements the 'magic' __len__()
method. So even objects you may not consider to be lists of elements could still be length-checked. This includes strings, queues, trees, etc.
Just use len(arr):
>>> import array
>>> arr = array.array('i')
>>> arr.append('2')
>>> arr.__len__()
1
>>> len(arr)
1
The preferred way to get the length of any python object is to pass it as an argument to the len function. Internally, python will then try to call the special __len__
method of the object that was passed.
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.
Python uses duck typing: it doesn't care about what an object is, as long as it has the appropriate interface for the situation at hand. When you call the built-in function len() on an object, you are actually calling its internal __len__ method. A custom object can implement this interface and len() will return the answer, even if the object is not conceptually a sequence.
For a complete list of interfaces, have a look here: http://docs.python.org/reference/datamodel.html#basic-customization