Search code examples
pythonbuilt-intry-except

Make the built in function len() in python


I'm trying to make a function to return the length of a list in python.

Code

def get_len(arr):
    ind = 0
    try:
        x = arr[ind]
        while x is not IndexError():
            ind += 1
            x = arr[ind]
    except IndexError:
        return ind

print(get_len([1, 2, 3, "one", "two"]))

Questions

  1. Is it wrong to use try / except to get the length ?
  2. Are there other ways to do it ?
  3. Which resources to see the implementation of built-in function len ?

Solution

  • The while x is not IndexError() part is unnecessary (x will never equal an IndexError()). Here's a simpler version:

    def get_len(arr):
        ind = 0
        while True:
            try:
                arr[ind]
            except IndexError:
                return ind
            ind += 1
    
    
    print(get_len([1, 2, 3, "one", "two"]))
    

    The statement arr[ind] is sufficient to check for an error; if ind is equal to or greater than len(arr), the subscript operator will raise (not return) an IndexError.

    The actual built-in function is typically not going to be one that's defined in Python itself. See for example the CPython implementation: https://github.com/python/cpython/blob/main/Objects/listobject.c#L429

    Note that the real len() function is much faster than a reimplemented version can be because the list already "knows" its length and can return it instantly without having to count up the items one by one.