Python built-in functions (37) -- len, python built-in 37len
English document:
-
len
(
S)
-
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) or a collection (such as a dictionary, set, or frozen set ).
-
Note:
-
-
1. The length of the returned object. parameters can be sequences (such as strings, byte arrays, tuples, lists, and range objects), or collections (such as dictionaries, sets, and immutable sets)
>>> Len ('abc') # string 4 >>> len (bytes ('abc', 'utf-8 ')) # byte array 4 >>> len (1, 2, 3, 4) # tuples 4 >>> len ([1, 2, 4]) # list 4 >>> len (range () # range object 4 >>> len ({'A': 1, 'B': 2, 'C ': 3, 'D': 4}) # dictionary 4 >>> len ({'A', 'B', 'C', 'D '}) # Set 4 >>> len (frozenset ('abc') # unchangeable set 4
2. If the parameter is of another type, it must implement the _ len _ method and return an integer. Otherwise, an error is returned.
>>> class A: def __init__(self,name): self.name = name def __len__(self): return len(self.name)>>> a = A('')>>> len(a)0>>> a = A('Aim')>>> len(a)3>>> class B: pass>>> b = B()>>> len(b)Traceback (most recent call last): File "<pyshell#65>", line 1, in <module> len(b)TypeError: object of type 'B' has no len()>>> class C: def __len__(self): return 'len'>>> c = C()>>> len(c)Traceback (most recent call last): File "<pyshell#71>", line 1, in <module> len(c)TypeError: 'str' object cannot be interpreted as an integer