It did exactly what you asked it to do.
Your function is not recursive as you forgot calling it again towards the end.
Something like this is what you are looking for:
def maxElement(L):
length=len(L)
if L[length-1]>L[length-2]:
del L[length-2]
print L
elif L[length-1]<L[length-2]:
del L[length-1]
if len(L) == 1:
return L
return maxElement(L)
print maxElement([1,2,95754754745,3,1,8,444,2,42425])
This would return:
[1, 2, 95754754745L, 3, 1, 8, 444, 42425]
[1, 2, 95754754745L, 3, 1, 8, 42425]
[1, 2, 95754754745L, 3, 1, 42425]
[1, 2, 95754754745L, 3, 42425]
[1, 2, 95754754745L, 42425]
[1, 95754754745L]
[95754754745L]
[95754754745L]
I would make it a bit more better as follows:
def maxElement(L):
length=len(L)
if length == 1:
# Have this condition on the top because you are using length - 2 later
# Just return the only element
return L
if L[length-1] > L[length-2]:
# If the last element is greater than the last but one, delete the last but one
del L[length - 2]
else:
# Simple else would suffice because you are just checking for the opposite
# Also this condition saves you from:
# infinite looping when the last two elements are equal
del L[length - 1]
print L
# Time to call it recursively.
# But if you just don't want to unnecessarily increase the recursion
# tree depth, check for length and return it
if length == 1:
return L
return maxElement(L)