List and dictionary comprehensions in Python combine readability with performance which is why they’ve already been covered is some of the previous articles, including
As such, so far I’ve never encountered a reason not to use them. A few days ago I’ve encountered an interesting snippet of code that looked something like the one below
Since function foo can return Nones, d can contain None values, which are not allowed in the result, so the result f is constructed through another comprehension that filters out None values.
But why can’t we perform filtering in the first comprehension? After all, imperative code certainly doesn’t require 2 dictionaries:
Sure, it doesn’t have dictionary comprehension elegance, but hey, surely it’s better than creating a temporary dictionary. And sure enough, it does perform much better:
vs
Almost 50% difference! But what if there was a way to do the same with dictionary comprehension? I remembered that a few versions ago Python introduced a somewhat controversial feature - assignment expression. In fact it was so controversial that it may have been one of the reasons Guido stepped down from his position as Benevolent Dictator For Life:
"The straw that broke the camel's back was a very contentious Python enhancement proposal, where after I had accepted it, people went to social media like Twitter and said things that really hurt me personally. And some of the people who said hurtful things were actually core Python developers, so I felt that I didn't quite have the trust of the Python core developer team anymore."
Guido van Rossum
Below is yet another proof that Guido was right to accept Walrus operator:
This way we achieve ultimate simplicity and best performance:
Feel free to play with these snippets on colab and consider using Walrus operator for the good.
Thanks for the post Tara’s. Big fan of the Python’s walrus operator