0

In the following code, i am computing nums.index() twice.

if ((elem in nums) and i != nums.index(elem)):
     j = nums.index(elem)
     return i,j

Is there a way through which I can initialize the variable in the expression itself and use it in the scope of the if condition? Maybe something like this

if ((elem in nums) and i != (j = nums.index(elem))):
   return i,j
  • Short answer: Use `j := nums.index(...)` instead of `j = nums.index(...)` for Python >= 3.8. For earlier Python versions initialise `j` before the `if` line (which, in my opinion, is more readable anyway). – Selcuk Feb 03 '22 at 06:44

1 Answers1

0

Yes you can do that using The Walrus Operator :=

elem = 10
nums = [11, 2, 10, 2, 3]


def fun():
    i = 3
    if (elem in nums) and i != (j := nums.index(elem)):
        return i, j


fun()
Mazhar
  • 1,044
  • 6
  • 11