how to find the length of a list in python without using len()

Question:

I want to write a function which will find out the length of a list based on user input. I don’t want to use the in-built function len().

Function which i have written is working for strings but for lists it is failing.

#function for finding out the length
def string_length(a):
    for i in a:
        j+=1
    return j

#taking user input
a = input("enter string :")
length = string_length(a)
print("length is ", length)
Asked By: Here_2_learn

||

Answers:

You probably need to initialize your variable j (here under renamed counter):

def string_length(my_string):
    """returns the length of a string
    """
    counter = 0
    for char in my_string:
        counter += 1
    return counter

# taking user input
string_input = input("enter string :")
length = string_length(string_input)

print("length is ", length)

This could also be done in one “pythonic” line using a generator expression, as zondo has pointed out:

def string_length(my_string):
    """returns the length of a string
    """
    return sum(1 for _ in my_string)
Answered By: Reblochon Masque

It’s quite simple:

def string_length(string):
    return sum(1 for char in string)

1 for char in string is a generator expression that generates a 1 for each character in the string. We pass that generator to sum() which adds them all up. The problem with what you had is that you didn’t define j before you added to it. You would need to put j = 0 before the loop. There’s another way that isn’t as nice as what I put above:

from functools import reduce # reduce() is built-in in Python 2.

def string_length(string):
    return reduce(lambda x,y: x+1, string, 0)

It works because reduce() calls the lambda function first with the initial argument, 0, and the first character in the string. The lambda function returns its first argument, 0, plus one. reduce() then calls the function again with the result, 1, and the next character in the string. It continues like this until it has passed every character in the string. The result: the length of the string.

Answered By: zondo

you can also do like this:

a=[1,2,2,3,1,3,3,]
pos=0 
for i in a: 
    pos+=1
print(pos) 
Answered By: Rishi Ratan Pandey

All responses that were given above work in O(N) time. My solution works in O(logN) time. Firstly we go through multiplying index by 2 until we run out of the array. Next we do a binary search for a point which exists on the array and next point which does not exist, giving us length of the array.

def logN_len(A, i = 0):
    while True:
        try: A[i]
        except: return binary_check(A, i//2, i)
        if not i: i += 1
        else: i*=2

def binary_check(A, l, p):
    while l < p:
        mid = (l + p) // 2
        try:
            A[mid]
            try:
                A[mid + 1]
                l = mid
            except: return mid + 1
        except: p = mid
    return 0
Answered By: Milek 5250

Just a simple answer:

def mylen(lst):

    a = 0
    for l in lst: a+=1
    return a

print(mylen(["a","b",1,2,3,4,5,6,67,8,910]))
Answered By: Dumindu
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.