print(testList, 'co do dai la', len(testList))
testList = [1, 2, 3]
print(testList, 'co do dai la', len(testList))
testTuple = (1, 2, 3)
print(testTuple, 'co do dai la', len(testTuple))
testRange = range(1, 10)
print('Do dai cua', testRange, 'la', len(testRange))
Run the program, the result is returned
[] co do dai la 0
[1, 2, 3] co do dai la 3
(1, 2, 3) co do dai la 3
Do dai cua range(1, 10) la 9
testString = ''
print('Do dai cua', testString, 'la', len(testString))
testString = 'Quantrimang'
print('Do dai cua', testString, 'la', len(testString))
# byte object
testByte = b'Quantrimang'
print('Do dai cua', testByte, 'la', len(testByte))
testList = [1, 2, 3]
# converting to bytes object
testByte = bytes(testList)
print('Do dai cua', testByte, 'la', len(testByte))
Running the program we get the result is:
Do dai cua la 0
Do dai cua Quantrimang la 11
Do dai cua b'Quantrimang' la 11
Do dai cua b'x01x02x03' la 3
testSet = {1, 2, 3}
print(testSet, 'co do dai la', len(testSet))
# Empty Set
testSet = set()
print(testSet, 'co do dai la', len(testSet))
testDict = {1: 'mot', 2: 'hai'}
print(testDict, 'co do dai la', len(testDict))
testDict = {}
print(testDict, 'co do dai la', len(testDict))
testSet = {1, 2}
# frozenSet
frozenTestSet = frozenset(testSet)
print(frozenTestSet, 'co do dai la', len(frozenTestSet))
The result returned is:
{1, 2, 3} co do dai la 3
set() co do dai la 0
{1: 'mot', 2: 'hai'} co do dai la 2
{} co do dai la 0
frozenset({1, 2}) co do dai la 2
When executed, len () calls the __len__ method of the object, so you can also imagine the len () function as:
def len(s):
return s.__len__()
Therefore, you can assign custom lengths to objects (if needed).
class Session:
def __init__(self, number = 0):
self.number = number
def __len__(self):
return self.number
# độ dài mặc định là 0
# viết bởi TipsMake.com
s1 = Session()
print(len(s1))
# gán chiều dài tùy chỉnh
s2 = Session(6)
print(len(s2))
Run the program, the returned result is:
0
6
Previous lesson: int () function in Python
Next lesson: function getattr () in Python