Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Custom len() Function In Python
Let's see how can we implement custom len() function in Python. Try it by yourself first using the following steps.
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.
Example
## 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.
Output
Enter a string:- tutorialspoint Length of tutorialspoint is 14
Advertisements