Python string length | len()
Python len() function returns the length of the string.
Python len() Syntax:
len(string)
len() Parameters:
It takes a string as the parameter.
len() Return Value:
It returns an integer which is the length of the string.
Python len() Example
Example 1: Len() function with tuples, list, and string
Python
# Python program to demonstrate the use of# len() method # Length of below string is 5string = "geeks"print(len(string))# with tupletup = (1,2,3)print(len(tup))# with listl = [1,2,3,4]print(len(l)) |
Output:
5 3 4
Example 2: Python len() TypeError
Python3
print(len(True)) |
Output:
TypeError: object of type 'bool' has no len()
Example 3: Python len() with dictionaries and sets
Python3
# Python program to demonstrate the use of# len() method dic = {'a':1, 'b': 2}print(len(dic))s = { 1, 2, 3, 4}print(len(s)) |
Output:
2 4
Example 4: Python len() with custom objects
Python3
class Public: def __init__(self, number): self.number = number def __len__(self): return self.number obj = Public(12)print(len(obj)) |
Output:
12


