Open In App

Write your own len() in Python

Improve
Improve
Like Article
Like
Save
Share
Report

The method len() returns the number of elements in the list or length of the string depending upon the argument you are passing. How to implement without using len():

Approach:

  1. Take input and pass the string/list into a function which return its length.
  2. Initialize a count variable to 0, this count variable count character in the string.
  3. Run a loop till the length if the string and increment count by 1.
  4. When loop is completed, return count.

Below is the implementation of the above approach:

Python




# Function which return length of string
def findLength(string):
 
    # Initialize count to zero
    count = 0
 
    # Counting character in a string
    for i in string:
        count += 1
    # Returning count
    return count
 
 
# Driver code
string = "geeksforgeeks"
print(findLength(string))


Output

13

Time Complexity: O(n)
Auxiliary Space: O(1)

Another Approach:

  1. Take input and pass the string/list into a function that returns its length.
  2. Initialize a count variable to 0, this count variable will count characters in the string.
  3. Now, the loop will run until the last element of the string is reached. once the index is greater than the string’s then the loop will terminate, and Except block will execute and print the length of the string.

Below is the implementation of the above approach:

Python3




def returnsLength(string):
    try:
        count = 0
        while(string[count]):
            count += 1
    except:
        print("Length of the String : ", count)
 
 
returnsLength("GeeksForGeeks")
 
# Contributed by SamyakJain



Time Complexity: O(n)
Auxiliary Space: O(1)

 Use recursion:

Recursion is a technique in which a function calls itself with a modified version of its input until a certain condition is met. It can be a useful approach for solving problems that involve repetitive steps or when you need to perform a task a certain number of times.

Here is an example of a recursive function that calculates the length of a string using recursion:

Python3




def recursive_length(string):
    if string == "":
    # base case: if the string is empty, the length is 0
        return 0
    else:
    # recursive case: remove the first character from the string and calculate the length of the remaining string
        return 1 + recursive_length(string[1:])
 
print(recursive_length("hello")) # prints 5


Output

5

 Time complexity: O(n), where n is the length of the input string. 
 Auxiliary space:O(1),



Last Updated : 19 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads