I'm reimplementing the min()
function as an exercise (EDIT: not all the functionality of the python std library function, just the minimum of a list of numbers). Here is my code:
def my_min(num_list):
minimum = num_list[0]
for num in num_list[1:]:
if num < minimum:
minimum = num
return minimum
My question is: How bad is num_list[1:]
in the for loop? And are there any other optimizations I could make to the code?
My intention by truncating the list is to avoid comparing the list's first element to itself. While insignificant in terms of wasted time and resources, I just find it lacking elegance.
for i in range(1, len(num_list))
) or advance an iterator manually (it = iter(xs); minimum = next(it); for x in it: ...
). The latter will also work on containers that don’t support slicing. \$\endgroup\$num_list
has zero elements? \$\endgroup\$