Python has a lot to give. Every week, I see code written in a way that I did not think was possible. Some of these functionalities are brilliant, and I cannot understand how I ever lived without them — others are simply nice to know.
This article will cover a few of these functionalities that are less commonly used, while still being immensely useful — including:
Variable Assignments - with *args and **kwargs (incl. dictionary merging)
Frozensets - what they are and why they're useful
Multiple Conditionals - cleaner logic
Check if a Variable Exists - in both local and global scopes
Better than Lambdas - writing Pythonic and functional one liners
Just like function *args and **kwargs — we can use the same syntax in our variable assignments:
Using the iterable variable assignment method can be particularly useful when merging dictionaries, where we can use the **kwargs syntax:
But we need to be cautious. If there are any common keys between the two dictionaries, the latter key-value pair (from y
) will replace the former.
With the newest, upcoming version of Python (3.9), we will get a fresh new syntax for this exact problem — the dictionary merge and update operators:
z = x | y # merge - same behavior as above
x |= y # update - in-place dictionary merge
In Python, we can use sets, which are unordered collections of distinct objects. These sets are mutable, which means we can change them with add()
and remove()
— this also means that the set is unhashable (more on this in a moment).
Alternatively, we can use the immutable frozenset()
— we cannot change its values. But, because it’s immutable, it’s hashable — which shows when we attempt to use both a set
and frozenset
as dictionary keys:
Okay, so using a frozenset
as a dictionary key is not that useful (if anyone has a reason for doing this, please let me know!). But what frozenset
does do is give us is more explicit, intentional code. It warns future readers of the code —
#python #programming #data-science