Python len()

The len() function returns the length (the number of items) of an object.

Example

languages = ['Python', 'Java', 'JavaScript']

length = len(languages)

print(length)  # Output: 3

len() Syntax

The syntax of len() is:

len(s)

len() Argument

The len() function takes a single object as argument. It can be:

  • Sequence - list, tuple, string, range, etc.
  • Collection - set, dictionary etc.

len() Return Value

It returns an integer (the length of the object).


Example 1: Working of len() with Tuples, Lists and Range

x = [1, 2, 3]
print(len(x)) # Output: 3

y = (1, 2, 3)
print(len(y)) # Output: 3

z = range(8, 20, 3)
print(len(z)) # Output: 4

Visit these pages to learn more about:


Example 2: len() with Strings, Dictionaries and Sets

text = 'Python'
print(len(text))  # Output: 6

person = {"name": 'Amanda', "age": 21}
print(len(person))  # Output: 2

animals = {'tiger', 'lion', 'tiger', 'cat'}
print(len(animals))  # Output: 3

Visit these pages to learn more about:


len() with User-defined Objects

The len() function internally calls the object's __len__() method. You can think of len() as:

def len(s):
    return s.__len__()

Therefore, we can make len() work for a user-defined object by implementing the ___len___() method.

Example 3: len() with User-defined Object

class Session:
    def __init__(self, number = 0):
      self.number = number
    
    def __len__(self):
      return self.number


# default length is 0
session1 = Session()
print(len(session1))  # Output: 0

session2 = Session(6)
print(len(session2))  # Output: 6
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges