I'm trying to make a function to return the length of a list in python.
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"]))
try
/ except
to get the length ?len
?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.