The lesson here for new programmers is: You can’t get the number of items in a list without counting them at some point. (The list object must be iterable, implied by the for.in stanza.) def count(list): # list is an iterable object but no type checking here! I would not condone this as a good option DO NOT PROGRAM LIKE THIS IN PYTHON, but it serves a purpose for learning algorithms. I explain why here but in short, if items or if not items is more readable and performant than other alternatives.Īnd for completeness (primarily educational), it is possible without using the len() function. Or if not items: # Then we have an empty list! Instead, simply do: if items: # Then we have some items, not empty! To test for a specific length, of course, simply test for equality: if len(items) = required_length:īut there's a special case for testing for a zero length list or the inverse. Builtin types you can get the len (length) ofĪnd 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,ĭo not use len to test for an empty or nonempty list Is considered to be false in a Boolean context.Īnd we can also see that _len_ is a method of lists: items._len_() Also, an object that doesn’tĭefine a _nonzero_() method and whose _len_() method returns zero Should return the length of the object, an integer >= 0. Len is implemented with _len_, from the data model docs:Ĭalled to implement the built-in function len(). The argument may be a sequence (such as a string, bytes, tuple, list, or range) orĪ collection (such as a dictionary, set, or frozen set). Return the length (the number of items) of an object. So checking the number of objects in a list is very fast.īut if you're checking if list size is zero or not, don't use len - instead, put the list in a boolean context - it is treated as False if empty, and True if non-empty. 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. All objects have a header of some sort in the C implementation. To find the number of elements in a list, use the builtin function len: items = Įverything in Python is an object, including lists.
0 Comments
Leave a Reply. |