Number of elements in list Python
To find the size of a list, use the builtin function, len: Show And now: len(items)returns 3. ExplanationEverything 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. len(s)
len is implemented with __len__, from the data model docs: object.__len__(self)
And we can also see that __len__ is a method of lists: items.__len__()returns 3. Builtin types you can get the len (length) ofAnd 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)) TrueDo not use len to test for an empty or nonempty listTo test for a specific length, of course, simply test for equality: 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! ...or 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. |