I'm trying to learn scripting in Python. So, I started using an exercise and it had this question for me. Define a function that computes the length of a given list or string. And I can't use the built in function len(). I tried the code below and I can't figure out what I'm doing wrong ! Please advise.

def length(x):
  sum(1 for x in "")
  print sum
2 Years
Discussion Span
Last Post by vegaseat


mystring = "briyani"
for c in mystring:

# then this should give you the length
length = sum(1 for c in mystring)

For a string, the following function works

def length(s):
    return 1 + s.rfind(s[-1]) if s else 0

It fails for a list because the list type has no method rfind(). The following works for a list

def length(alist):
    x = object()
    result = alist.index(x)
    del alist[-1]
    return result

You must add ix = -1 before the for loop, or enumerate from 1:

ix = 0
for ix, c in enumerate(s, 1): pass
length = ix

Edited by Gribouillis


Hello Ram_10.

Hope that you follow the code

def length(t):
    my_list = list(t) # Makes a list of the string
    x = 0                          
    for i in my_list: # i steps through the list
        x = x + 1     # count the steps

    return x          # return the last count

print length('anders') # will return 6 in this case

Best regards



Thanks guys ! That's so much of input for one post and I learned a lot from this thread. Once again, thank you all :)


Even simpler ...

def length(seq):
    n = 0
    for c in seq:
        n += 1
    return n

s = "vegaseat"
print(length(s))  # result --> 8

You can also apply a recursive function and slicing ...

def length(seq, n=0):
    '''uses recursive function and slicing'''
    if not seq:
        return n
    return length(seq[:-1], n+1)

s = "vegaseat"
print(length(s))   # result --> 8

A bit more modern using the ternary if/else ...

def length(seq, n=0):
    '''uses recursive function and slicing'''
    return n if not seq else length(seq[:-1], n+1)

s = "vegaseat"
print(length(s))   # result --> 8

Note that a recursive function calls itself with changed arguments and has an exit condition.
All in all a nice problem to play with to study Python code. Thanks for bringing it up!

Edited by vegaseat: ternary if/else

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.