In Python, is the following the only way to get the number of elements?
arr.__len__()
If so, why the strange syntax?
To find the length of an array in Python, we can use the len() function. It is a built-in Python method that takes an array as an argument and returns the number of elements in the array. The len() function returns the size of an array.
Len() Method There is a built-in function called len() for getting the total number of items in a list, tuple, arrays, dictionary, etc. The len() method takes an argument where you may provide a list and it returns the length of the given list.
The length property of an array is an unsigned, 32-bit integer that is always numerically greater than the highest index of the array. The length returns the number of elements that a dense array has.
my_list = [1,2,3,4,5] len(my_list) # 5
The same works for tuples:
my_tuple = (1,2,3,4,5) len(my_tuple) # 5
And strings, which are really just arrays of characters:
my_string = 'hello world' len(my_string) # 11
It was intentionally done this way so that lists, tuples and other container types or iterables 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.
The functional nature of len()
also lends itself well to functional styles of programming.
lengths = map(len, list_of_containers)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With