Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

arr.__len__() 

If so, why the strange syntax?

like image 275
Joan Venge Avatar asked Feb 05 '09 21:02

Joan Venge


People also ask

How do I find the length of an array in Python?

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.

What method used to return the length of an array in Python?

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.

What does Arr length do?

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.


1 Answers

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) 
like image 91
Soviut Avatar answered Sep 20 '22 02:09

Soviut