Is arr.__len__() the preferred way to get the length of an array in Python?

前端 未结 8 1018
悲哀的现实
悲哀的现实 2020-12-04 05:18

In Python, is the following the only way to get the number of elements?

arr.__len__()

If so, why the strange syntax?

8条回答
  •  悲&欢浪女
    2020-12-04 05:30

    Python suggests users use len() instead of __len__() for consistency, just like other guys said. However, There're some other benefits:

    For some built-in types like list, str, bytearray and so on, the Cython implementation of len() takes a shortcut. It directly returns the ob_size in a C structure, which is faster than calling __len__().

    If you are interested in such details, you could read the book called "Fluent Python" by Luciano Ramalho. There're many interesting details in it, and may help you understand Python more deeply.

提交回复
热议问题