1) The walrus operator :=
The walrus operator does 2 things. In x := 5
it assigns teh variable x to the value 5
the expression (x := 5) returns the value of x itself.
This operator essentially helps us save one line of code.
2) divmod()
When learning Python basics, we probably learnt
the // operator does floor division (or integer division)
the % operator gives us the remainder when a number is divided by another
But did you know that there’s a built-in function that does both at the same time? We can do this using the divmod() function, which returns a (quotient, remainder) tuple.
3) % to format strings
The % operator can also be used to format template strings.
This is a slightly older way of formatting strings, as we tend to use string.format() now instead.
But this way of formatting strings is still legal, and might be found in slightly older Python code bases.
4) @ for matrix multiplication
This might be surprising, but Python has a matrix multiplication operator. We use the @ symbol for this (not to be confused with decorators)
While our usual data types eg int, float etc might not be able to do matrix multiplication, data types from the numpy library can.
Also, if we define the __matmul__ magic method in classes, we can customize behaviour when we use this @ operator for our custom objects
Quick Pause
I recently wrote a book — 101 Things I Never Knew About Python
Here I’ve compiled 101 cool Python tricks and facts that many (if not most) do not know about. Check it out if you wish to level up your Python knowledge!
Link: https://payhip.com/b/vywcf
5) Operators and magic methods
Whenever we use the built-in operators in Python, we are actually calling their corresponding magic method in the backend.
__add__ for the + operator
__sub__ for the - operator
__mul__ for the * operator
__truediv__ for the / operator
__floordiv__ for the // operator
By extension, we can define these magic methods in our custom classes so that we can use the corresponding operator on our custom objects.
6) Compound assignment operators
Let’s say we have an existing integer variable x. And we wish to increment x by 1.
We can also use a compound assignment operator to do this.
This applies to all other numerical operators too.
x += 1 is the same as x = x + 1
x -= 1 is the same as x = x - 1
x *= 1 is the same as x = x * 1
x /= 1 is the same as x = x / 1
x //= 1 is the same as x = x // 1
x %= 1 is the same as x = x % 1
x **= 1 is the same as x = x ** 1
And similarly, each compound assignment operator has its own magic methods that works in the background.
x += 1 uses __iadd__
x -= 1 uses __isub__
x *= 1 uses __imul__
x /= 1 uses __itruediv__
x //= 1 uses __ifloordiv__
x %= 1 uses __imod__
x ** 1 uses __ipow__
7) -> for type hinting
Yes, there is a use for the -> operator. We use this operator to denote the type hint of a function’s return type.
^ notice the -> float that we place in our function definition.
This just means that this specific function is meant to return a float value.
^ and in such a case, the -> list[int] means that our function is meant to return a list of integers.
Note — type hints hint but don’t enforce. Which means that it is legal to make this function return a string instead (though this is terrible practice)
8) Ternary operator
Let’s say we have a simple if-else block that assigns some value to grade.
Using the ternary operator, we can replace the if-else block with one line of code.
Note that we can have multiple ifs and elses in one ternary operator expression.
9) The ‘None or value’ expression
If we use the expression None or ‘apple’, this expression defaults to ‘apple’ because the first value is a falsy value:
Conversely, if we replace None with a truthy value, our expression no longer takes on the value ‘apple’:
This ( variable or value ) expression is often used to ensure that variable is not None. Let’s illustrate this with a simple example. Let’s say we have a function that has a chance of returning None.
^ and here, we use the ( get_fruit() or ‘apple’ ) expression:
if get_fruit() returns None, fruit is assigned to the default value ‘apple’
if get_fruit() returns either orange or pear, fruit simple takes that value.
10) De Morgan’s law
This is important with we’re dealing with brackets and the not operator.
not ( A and B ) equals ( not A or not B )
not ( A or B ) equals ( not A and not B )
Notice that when we expand the not keyword to the values inside the brackets, and becomes or, and or becomes and.
Let’s illustrate this with an example. Let’s say I am allergic to both peanuts and garlic. If a dish has either peanuts or garlic, I cannot eat it:
Let’s add a not in front of this condition, and flip it around. If the condition (HAS_PEANUTS or HAS_GARLIC) is False, I can eat the dish.
Next, let’s expand this using De Morgan’s Law. Remember that when when expanding brackets in these cases, we must switch and with or, and vice versa.
What the code means now — if our dish 1) has no peanuts 2) has no garlic, only then I can eat the dish. Notice that it makes sense logically.
Keep reading with a 7-day free trial
Subscribe to The Python Rabbithole to keep reading this post and get 7 days of free access to the full post archives.