Python built-in function len 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 ('ABCD') # string >>> len (bytes ('abcd', 'utf-8') # byte array >>> len, (3, 4) # tuples >>> len ([, 3, 4]) # List >>> len (range )) # range object >>> len ({'a': 1, 'B': 2, 'C': 3, 'D': 4 }) # Dictionary >>> len ({'a', 'B', 'c', 'D'}) # set >>> len (frozenset ('ABCD ')) # immutable set
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)>>> a = A('Aim')>>> len(a)>>> class B: pass>>> b = B()>>> len(b)Traceback (most recent call last): File "
", line 1, in
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 "
", line 1, in
len(c)TypeError: 'str' object cannot be interpreted as an integer