How do you 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.
Ok, having cleared that, getting the the size of a
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']
Size of tuple
>>> movie = ('Terminator', 'James Cameron', 'Arnold Schwarzenegger')
So there it is, you just call the global function
len() on the
tuple and you get its size / length.
Did you expect to have something like
tuple.len() instead? Actually there is something like that, but it is called
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
tuple in Python (you probably didn't mean Python
array), you just call the
len() function on the object.
array, probably you mean
- You can make your custom objects return values to the
- Create a custom object which returns weird values for
len()and shock your family and friends.
- Why isn't there
tuple.len(), instead there is