Monday, September 23, 2024
Google search engine
HomeLanguagesPython string length | len()

Python string length | len()

Python len() function returns the length of the string

Python len() Syntax

Syntax: len(string) 

Return: It returns an integer which is the length of the string. 

Python len() Example

len() methods with string in Python.

Python3




string = "Geeksforgeeks"
print(len(string))


Output:

13

Example 1: Len() function with tuples and string

Here we are counting length of the tuples and list.

Python




# Python program to demonstrate the use of
# len() method  
  
# with tuple
tup = (1,2,3)
print(len(tup))
  
# with list
l = [1,2,3,4]
print(len(l))


Output: 

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

Time complexity : 

len() function  has time complexity of O(1). in average and amortized case

RELATED ARTICLES

Most Popular

Recent Comments