Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python string length | len()

  • Difficulty Level : Basic
  • Last Updated : 27 Sep, 2021

Python len() function returns the length of the string. 

Python len() Syntax: 

len(string) 

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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 5
string = "geeks"
print(len(string))
 
# with tuple
tup = (1,2,3)
print(len(tup))
 
# with list
l = [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



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!