How do I get the number of elements in a list?
How to get the size of a list?
To find the size of a list, use the builtin function,
items = items.append("apple")items.append("orange")items.append("banana")
Everything in Python is an object, including lists. All objects have a header of some sort in the C implementation.
Lists and other similar builtin objects with a "size" in Python, in particular, have an attribute called
ob_size, where the number of elements in the object is cached. So checking the number of objects in a list is very fast.
But if you're checking if list size is zero or not, don't use
len - instead, put the list in a boolean context - it treated as False if empty, True otherwise.
From the docs
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) ora collection (such as a dictionary, set, or frozen set).
len is implemented with
__len__, from the data model docs:
Called to implement the built-in function
len(). Should return the length of the object, an integer >= 0. Also, an object that doesn’tdefine a
__nonzero__()[in Python 2 or
__bool__()in Python 3] method and whose
__len__()method returns zerois considered to be false in a Boolean context.
And we can also see that
__len__ is a method of lists:
Builtin types you can get the
len (length) of
And in fact we see we can get this information for all of the described types:
all(hasattr(cls, '__len__') for cls in (str, bytes, tuple, list, range, dict, set, frozenset))True
Do not use
len to test for an empty or nonempty list
To test for a specific length, of course, simply test for equality:
if len(items) == required_length: ...
But there's a special case for testing for a zero length list or the inverse. In that case, do not test for equality.
Also, do not do:
if len(items): ...
Instead, simply do:
if items: # Then we have some items, not empty! ...
if not items: # Then we have an empty list! ...
I explain why here but in short,
if items or
if not items is both more readable and more performant.
While this may not be useful due to the fact that it'd make a lot more sense as being "out of the box" functionality, a fairly simple hack would be to build a class with a
class slist(list): def length(self): return len(self)
You can use it like so:
range(10)) l.length10print l[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]l = slist(
Essentially, it's exactly identical to a list object, with the added benefit of having an OOP-friendly
As always, your mileage may vary.