In Python, is the following 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.
Sure, this may seem redundant, but length checking implementations can vary considerably, even within the same language. It's not uncommon to see one collection type use a .length() method while another type uses a .length property, while yet another uses .count(). Having a language-level keyword unifies the entry point for all these types. So even objects you may not consider to be lists of elements could still be length-checked. This includes strings, queues, trees, etc.