What does the walrus operator `:=` do?
IntermediateConceptLanguage essentials & functions
Answer
It assigns inside an expression, which removes duplicate calls in loops and comprehensions:
while (chunk := f.read(65536)):
h.update(chunk)
if (m := re.search(r"ERROR (\w+)", line)):
codes[m.group(1)] += 1
big = [s for v in volumes if (s := v["Size"]) > 500]
Use it where it removes repetition; do not chain it into unreadable one-liners.
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner