Python len() function returns the length of the string. In this article, we will see how to find the length or number of items stored in a data structure.
Python len() Syntax
Syntax: len(string)
Return: It returns an integer which is the length of the string.
Python len() Example
The len() method is used to find the length of an object in Python. By using len(), we can find the length of strings and lists. In this example, we are finding the length of a string.
Python3
string = "Geeksforgeeks"
print(len(string))
|
Example 1: Len() function with tuples and string
In this example, we are counting length of the tuples and list.
Python
tup = (1,2,3)
print(len(tup))
l = [1,2,3,4]
print(len(l))
|
Example 2: Python len() TypeError
In this example, we are using len() with boolean value and find TypeError as a result.
Output
TypeError: object of type 'bool' has no len()
Example 3: Python len() with dictionaries and sets
In this example, we are using Python len() with dictionaries and sets to find the length of dictionary and set.
Python3
dic = {'a':1, 'b': 2}
print(len(dic))
s = { 1, 2, 3, 4}
print(len(s))
|
Example 4: Python len() with custom objects
In this example, we are using len() to find the length of custom objects and to find the length of an object in Python.
Python3
class Public:
def __init__(self, number):
self.number = number
def __len__(self):
return self.number
obj = Public(12)
print(len(obj))
|
Example 5: Python len() with range()
In this example, we are using len() function to find the length of the range() function.
Python3
l=range(1,10)
print(len(l))
|
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.Dive into the future of technology - explore the
Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Last Updated :
30 Nov, 2023
Like Article
Save Article