Python walrus update if

Feb 4, 2022

A pretty (common) use case is to have a variable update only upon a condition. For example updating a minLength value:

if minLength > len(cat)- len(dog):
  minLength = len(cat) - len(cat)

Which is inefficient because it has to do the calculation twice, plus you have to type it out. Typically the optimization would be

lenDiff = len(cat) - len(dog):
if minLength > lenDiff:
  minLength = lenDiff

With python’s walrus operator, you can do an assign statement inside an if statement

if minLength > lenDiff:= len(cat) - len(dog):
  minLength = lenDiff

Which just comes across to me as more elegant and straightforward to write. Typically when hearing about the walrus operator, which is relatively new to python, I would only see the example of it being used in a while loop, so I thought this would be handy. Walrus operators where introduced in Python3.8, which came out Oct 2019

Unfortunately lenDiff is still scoped outside of the if-statement, so there is an amount of namespace pollution just like with other solutions.


← Back ← Go to all posts