Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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

In Python, is the accompanying the best way to get the number of elements?
arr.__len__()

Assuming this is the case, why the weird strange syntax?
by

3 Answers

akshay1995

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
sandhya6gczb
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.
RoliMishra
Just use len(arr):

>>> import array
>>> arr = array.array('i')
>>> arr.append('2')
>>> arr.__len__()
1
>>> len(arr)
1

Login / Signup to Answer the Question.