I was doing question number 238 on leetcode and I wanted to use the walrus operator as practice. Here’s the part of the code that I have an issue with:
def productExceptSelf(self, nums: List[int]) -> List[int]:
zero = 0 # number of zeros, increments for every 0 it encounters
final = 1 # gets the product of every element in nums that's not a zero
[final := final * digit if digit != 0 else (zero := zero + 1) for digit in nums]
Consider nums = [-1, 1, 0, -3, 3]
as a case. For this list, ideally I want the value of final
to be 9. But it comes out to be -9. However, if I change that list comprehension just slightly by adding parenthesis around the final
walrus statement:
[(final := final * digit) if digit != 0 else (zero := zero + 1) for digit in nums]
then my final
value comes out to be 9, which is what I wanted.
How does simply adding the extra parenthesis make my result come out to be what I want it to be, and why does it’s absence not give me an error, but somehow -9 in this case?