0

Why does the function return none?

I thought list were passed by reference. I added return to the recursive call, it worked. But I'm just wondering why the return did made a difference.

Note: I'm trying to learn recursion

def find_min_max(arr, i, nums):
  if i == len(arr):
    return nums

  if arr[i] < nums[0]:
    nums[0] = arr[i]
  if arr[i] > nums[1]:
    nums[1] = arr[i]

  find_min_max(arr, i+1, nums)
Emma
  • 27,428
  • 11
  • 44
  • 69
DeviantG
  • 13
  • 5
  • Why do you have `return nums` instead of just `nums` ? What does `return` do? In the bottom of every python function there is an invisible `return None` – Sylwester Jul 15 '19 at 11:37

2 Answers2

6

You miss a return statement in the last line, if you don't return anything, python by default returns None

def find_min_max(arr, i, nums):
  if i == len(arr):
    return nums

  if arr[i] < nums[0]:
    nums[0] = arr[i]
  if arr[i] > nums[1]:
    nums[1] = arr[i]

  return find_min_max(arr, i+1, nums)
developer_hatch
  • 15,898
  • 3
  • 42
  • 75
0

I added return to the recursive call, it worked. But I'm just wondering why the return did made a difference.

It is the same as if you had called any other function in that spot; the value only gets returned if you specify to return it. There is nothing special about calling a function recursively vs. any other calling of functions; there is only something special about writing correct logic that uses the technique :)

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153