English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The len() function returns the number of items or length of an object.
The syntax of len() is:
len(s)
s-Sequence (string, bytes, tuple, list, or range) or set (dictionary, set, or frozen set)
The len() function returns the number of items in an object.
Not passing a parameter or passing an invalid parameter will raise a TypeError exception.
testList = [] print(testList, 'number of items', len(testList)) testList = [1, 2, 3] print(testList, 'number of items', len(testList)) testTuple = (1, 2, 3) print(testTuple, 'number of items', len(testTuple)) testRange = range(1, 10) print('Item', testRange, 'number of items', len(testRange))
The output when running the program is:
[] number of items is 0 [1, 2, 3] number of items 3 (1, 2, 3) number of items 3 Item range(1, 10) number of items 9
Visit these pages to learn more about the following content:
testString = '' print('string', testString, 'length is', len(testString)) testString = 'Python' print('string', testString, 'length is', len(testString)) # byte object testByte = b'Python' print('string', testByte, 'length is', len(testByte)) testList = [1, 2, 3] # Convert to byte object testByte = bytes(testList) print('string', testByte, 'length is', len(testByte))
The output when running the program is:
string length is 0 string 'Python' length is 6 string 'b'Python' length is 6 string 'b'\x01\x02\x03Length is 3
Visit these pages to learn more about the following content:
testSet = {1, 2, 3} print(testSet, 'Length is', len(testSet)) # Empty Set testSet = set() print(testSet, 'Length is', len(testSet)) testDict = {1: 'one', 2: 'two'} print(testDict, 'Length is', len(testDict)) testDict = {} print(testDict, 'Length is', len(testDict)) testSet = {1, 2} # frozenSet frozenTestSet = frozenset(testSet) print(frozenTestSet, 'Length is', len(frozenTestSet))
The output when running the program is:
{1, 2, 3} Length is 3 set() Length is 0 {1: 'one', 2: 'two' Length is 2 {} Length is 0 frozenset({1, 2}) Length is 2
Visit these pages to learn more about the following content:
Internally, len() calls the object's __len__ method. You can understand len() as:
def len(s): return s.__len__()
Therefore, you can assign a custom length to the object (if necessary)
class Session: def __init__(self, number = 0): self.number = number def __len__(self): return self.number # Default length is 0 s1 = Session() print(len(s1)) # Given length s2 = Session(6) print(len(s2))
The output when running the program is:
0 6