Python len()

Parameters:

len() accepts one of following as a parameter at a time-

  1. a sequence (string, bytes, list, tuples or range)
  2. collection(dictionary, sets or frozen set)

Return:

Returns a number

Example of len() with different python data structure:

l = [1, 2, 3, 4]print(f'Length of list is {len(l)}')t = (1, 2, 3)print(f'Length of tuple is {len(t)}')s = {1, 2, 3, 4, 5}print(f'Length of set is {len(s)}')d = {1: 'a', 2:'b', 3:'c'}print(f'Length of dictionary is {len(d)}')

Output:

Length of list is 4
Length of tuple is 3
Length of set is 5
Length of dictionary is 3

How to use len() with custom objects:

To use len(), __len__ functions is required to be defined in the custom class. Following is the example-

class Sample:
def __init__(self):
#do_someting
self.length = 2
def __len__(self):
return self.length
a = Sample()
print(len(a))

Output:

2

Here, I hard coded the value of length for each Sample class object but it is not necessary value of length attribute could be changed and output will change accordingly.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store