Custom len() Function In Python

PythonServer Side ProgrammingProgramming

Let's see how can we implement custom len() function in Python. Try it by yourself first using the following steps.


  • Get the iterator from the user string/list/tuple.

  • Define a function with a custom name as you like and invoke it by passing the iterator.

    • Initialize the count to 0.
    • Run a loop until it reaches the end.
      • Increment the count by 1
    • Return the count.


 Live Demo

## function to calculate lenght of the iterator
def length(iterator):
   ## initializing the count to 0
   count = 0
   ## iterating through the iterator
   for item in iterator:
      ## incrementing count
      count += 1
   ## returning the length of the iterator
   return count
if __name__ == "__main__":
   ## getting input from the user
   iterator = input("Enter a string:- ")
   ## invoking the length function with 'iterator'
   print(f"Length of {iterator} is {length(iterator)}")

If you run the above program, you will get the following results.


Enter a string:- tutorialspoint
Length of tutorialspoint is 14
Updated on 30-Jul-2019 22:30:26