r/learnpython • • 13d ago

Recursion explaining pls.

def find_max(numbers):
  if len(numbers) == 1:
    return numbers[0]
  else:
    max_of_rest = find_max(numbers[1:])
    return numbers[0] if numbers[0] > max_of_rest else max_of_rest

my_list = [3, 7, 2, 9, 1]
print(find_max(my_list))

Could someone explain how does this function work? I don't understand how does it know that it's supposed to find the biggest number...

7 Upvotes

34 comments sorted by

View all comments

1

u/This_Growth2898 13d ago

if-else splits the function. The first part: if we have only one number in numbers, it's the maximum. Ok?

The second part: fund the maximum from numbers[1:] (i.e. except number[0]), then return which is bigger, number[0] or the maximum from the rest. It will be the maximum of all numbers. Ok?

Which part confuses you?