Python: Length or size of list, tuple, array
How to get the length of a list or tuple or array in Python#
Let me clarify something at the beginning, by array
, you probably mean list
in Python. list
is the equivalent of arrays in JavaScript or PHP. Arrays in Python is an altogether different thing.
Ok, having cleared that, getting the the size of a list
or tuple
(or array
, if you will), is pretty straighforward. You just call the len()
function on the object, and there you have it's size. Examples of list and tuple size / lengths are given below.
Size of list:
>>> fighters = ['bruce', 'chuck', 'benny']
>>> len(fighters)
3
Size of tuple:
>>> movie = ('Terminator', 'James Cameron', 'Arnold Schwarzenegger')
>>> len(movie)
3
So there it is, you just call the global function len()
on the list
or tuple
and you get its size / length.
Did you expect to have something like list.len()
or tuple.len()
instead? Actually there is something like that, but it is called list.__len__()
or tuple.__len__()
. And what len()
really does is, it takes the object and tries to call the objects's __len__()
method. So essentially, len()
works only on objects that has a __len__()
method. If you have a custom object that has the __len__()
method, you can call len()
even on that.
So you learnt: to get the size or length of a list
or tuple
in Python (you probably didn't mean Python array
), you just call the len()
function on the object.
Notes#
- If you came from PHP / JavaScript, by
array
, probably you meanlist
in Python. - You can make your custom objects return values to the
len()
function.
Exercise#
- Create a custom object which returns weird values for
len()
and shock your family and friends. - Why isn't there
list.len()
ortuple.len()
, instead there islist.__len__()
ortuple.__len__()
?