What are lambdas good for, and when should you avoid them?
BeginnerConceptLanguage essentials & functions
Answer
A lambda is a one-expression anonymous function. Good uses are short key functions:
newest = max(snapshots, key=lambda s: s["StartTime"])
by_cost = sorted(items, key=lambda x: (x["severity_rank"], -x["cost"]))
Avoid assigning lambdas to names (f = lambda x: ...; use def), multi-step logic, and lambdas created in loops that capture the loop variable. operator.itemgetter("StartTime") is a faster, clearer alternative for key lookups.
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