-1

I want to have the following heading where the default value of a parameter depends on another parameter:

def function2(x,l=0,r=len(x)-1)

This obviously returns an error. Is there any way to go around this?

Thank you

zest16
  • 455
  • 3
  • 7
  • 20
  • 4
    Why dont you define `r` inside `function2`? – Gocht Jan 16 '20 at 23:06
  • But that would override those cases where `r` is not equal to `len(x)-1`, right? – zest16 Jan 16 '20 at 23:08
  • @zest16 You can play around with the parameter inside the function. `def function2(x, l, r): r = len(x)-1 ... – dper Jan 16 '20 at 23:09
  • 2
    Does this help? https://stackoverflow.com/questions/21804615/how-can-i-make-the-default-value-of-an-argument-depend-on-another-argument-in-p – Anis R. Jan 16 '20 at 23:10

2 Answers2

3

This workaround maybe can help:

def function2(x, l=0, r=None):
    if r is None:
        r = len(x) - 1
    ...

This will set r to len(x) - 1 only when r is not set, i.e:

function2(x='hi', l=0)  # r will take value len(x) - 1
function2(x='hi', l=0, r=5)  # r will take value 5
Gocht
  • 9,924
  • 3
  • 42
  • 81
0

I am not sure if this solution will completely help you.

If a variable depends on another input variable it might be interesting to do something like:

def function2(x,l=0):
     r = len(x) - 1
     ...

jalazbe
  • 1,801
  • 3
  • 19
  • 40
  • OP still wants `r` to be a parameter of the function, but with a default value of `len(x) - 1`. – Anis R. Jan 16 '20 at 23:11