When programming, you may come across a situation in which you need to determine the length of a specific iterable object. For example, consider you want to find out the average marks of the students in a class. For this, we will also need the number of students studying in the classroom. The same situation might be implemented in the Python program. Python len() is a built-in function that helps resolve this issue without any hassle. It is used to calculate the length of any iterable object passed as a parameter to the len() function.
Definition
- Python len() is a built-in function that returns the number of elements (length) in an iterator/object passed to the function.
- The Python len() function is used to return a numeric value that denotes the length of the given list, tuple, string, array, dictionary, etc.
Python len()
The len() function is used to return an integer value which indicates the number of items in an object. Data items are stored as numeric index values in the iterable objects such as string, list, tuple, etc. These index values are useful to reference individual data items of the object. The Python len() function sums up these index values of a specified iterator and returns the count.
SyntaxÂ
len(object)
len() parameters
Python len() function accepts a single parameter. It accepts an object of sequence (string, range, bytes, tuple, list) or a collection of data items (dictionary, set)
Return value from len() function
The number of items in an object is returned by the len() function. A TypeError exception will be thrown if an argument is not given or if an invalid argument is passed.
Example 1: How does len() work with lists, tuples, and range?
Example
# Python program to illustrate len()
my_list = []
print('Total items in', my_list, 'is :', len(my_list))
list2 = [1, 2, 3, 4, 5, 6]
print('Total items in', list2, 'is :', len(list2))
my_tuple = ('Sam', 'Vicky', 'Sharon', 'Riya')
print('Total items in', my_tuple, 'is :', len(my_tuple))
my_range = range(1, 9)
print('Total items in', my_range, 'is :', len(my_range))
Output
Total items in [] is : 0
Total items in [1, 2, 3, 4, 5, 6] is : 6
Total items in ('Sam', 'Vicky', 'Sharon', 'Riya') is : 4
Total items in range(1, 9) is : 8
Example 2: How does len() work with strings and bytes?
Python len() function also works with strings. It returns the count i.e. number of characters of that string. If there exists any space between 2 words in a string of characters, then the len() function will also include it in the count.
Example
# Python program to illustrate len()
string = 'Hello World'
print('Length of', string, 'is :', len(string))
my_bytes = b'Good Evening'
print('Length of', my_bytes, 'is :', len(my_bytes))
Output
Length of Hello World is : 11
Length of b'Good Evening' is : 12
Example 3: How does len() work with dictionaries and sets?
Example
my_set = {2, 4, 6, 8}
print('Length of', my_set, 'is:', len(my_set))
my_dict = {'Name': 'Rocky', 'Age': 45, 'City': 'LA'}
print('Length of', my_dict, 'is:', len(my_dict))
my_dict2 = {}
print('Length of', my_dict2, 'is:', len(my_dict2))
Output
Length of {8, 2, 4, 6} is: 4
Length of {'Name': 'Rocky', 'Age': 45, 'City': 'LA'} is: 3
Length of {} is: 0
Example 4: How len() works for custom objects?
Python’s len() function can be depicted as follow:
def len(s):
   return s.__len__()
Internally, len() calls __len__ method of an object.
Example
class Details:
   def __init__(self, alphabet = 0):
       self.alphabet = alphabet  Â
   def __len__(self):
       return self.alphabet
d1 = Details()
print('Default length of word - alphabet - in class Details is:', len(d1))
d2 = Details(8)
print('Length of word - alphabet - in class Details is:', len(d2))
Output
Default length of word - alphabet - in class Details is: 0
Length of word - alphabet - in class Details is: 8
Example 5: TypeError Exception
Few iterables such as int, float, bool does not support the len() function. It will throw a TypeError exception if used along with the len() function.
Example
val = 20
print(len(val))
Output
Traceback (most recent call last):
File "", line 2, in
TypeError: object of type 'int' has no len()
Example
print(len(True))
Output
Traceback (most recent call last):
File "", line 1, in
TypeError: object of type 'bool' has no len()
Python len() in for loop
Python’s len() function can also be used in the for loop in order to specify the range from which the for loop will be executing its iterations. Let us look at the following example to understand this concept.
Example
car_brand = ['BMW', 'Audi', 'Ford', 'Tata', 'Jaguar', 'Porsche']
for i in range(0, len(car_brand)):
   print('Car brand:', car_brand[i])
Output
Car brand: BMW
Car brand: Audi
Car brand: Ford
Car brand: Tata
Car brand: Jaguar
Car brand: Porsche
In the above program, the len() function first finds out the number of items in the list ‘car_brand’, returns the integer value to the range function which in turn tells the for loop its number of iteration to be performed. In this case, the range will be from 0 to 6, because there are 6 number of data items in the list.
Frequently Asked Questions
Q1. What is len() function?
Consider we want to find out the number of products a brand manufactures. There might be many names on that list. This issue can be solved by using Python’s len() function. Python len() is a built-in function that helps resolve these types of issues without any hassle. It is used to calculate the length (number of items) of any iterable object passed as a parameter to the Python len() function.
Q2. How do you implement len in Python?
Python len() built-in function can be implemented in the following way –
SyntaxÂ
len(object)
len() parameters
Python len() function accepts a single parameter. It accepts an object of sequence (string, range, bytes, tuple, list) or a collection of data items (dictionary, set)
Example –
txt = 'Programming'
print('Length of txt:', len(txt))
food = ['cake', 'bread', 'egg', 'butter', 'jam']
print('Length of food list:', len(food))
Output
Length of txt: 11
Length of food list: 5
Q3. What is the use of a len list in Python?
Python includes a built-in function len() that returns the total number of elements in a list, tuple, array, dictionary, or other data structure. The len() method accepts an argument, which might be a list, and returns the length of the given list.
Example
my_list = [1, 2, 'Sam', 'a', 5634, 'car', 1.53]
print('Number of items in the list:', len(my_list))
Output
Number of items in the list: 7
Another way in which we can use the len() function along with the list iterator is –
Example
words = ['Toppr', 'Python', 'Programming', 'Computer']
for i in words:
   print(i, '=', len(i))
print ('')
print ('Length of the list = ', len(words))
Output
Toppr = 5
Python = 6
Programming = 11
Computer = 8
Length of the list = 4
Here we have used the len() function to calculate the number of characters for an individual data item in the list, and then calculate the total number of items stored in the list.
Leave a Reply