Search code examples
pythonlistdefault-arguments

Python default parameter assigning length of list


I get an error saying the arr for p2 is undefined. If I move the p2 = len(arr) - 1 expression into inside the function, the error goes away. Why do I get this error and how do I make this default argument expression work?

   def sumZero_refactor(arr, p1 = 0, p2 = len(arr) -1):
NameError: name 'arr' is not defined
def sumZero_refactor(arr, p1 = 0, p2 = len(arr) -1):
  while p1 < p2:
    if arr[p1] + arr[p2] == 0:
      return [arr[p1], arr[p2]]
    elif arr[p1] + arr[p2] < 0:
      p1 += 1
    else:
      p2 -= 1


print(sumZero_refactor([-3, -2, -1, 0, 1, 2, 3]))
print(sumZero_refactor([-2, 0, 1, 3]))
print(sumZero_refactor([1, 2, 3]))
print(sumZero_refactor([-8, -7, -5, -2, 0, 1, 2, 3, 4, 5, 6]))


Solution

  • Some languages, like Ruby, allow a parameter list to reference previously named parameters. Unfortunately, Python does not.

    You'll have to add p2 = len(arr) - 1 inside the function body.