Member-only story
5 Obscure Python Syntaxes You Should Try
Intriguing methods for accomplishing common tasks

The Python programming language syntax is straightforward, clean and relatively easy to get started with.
Although style guides like PEP 8 can be rather strict for what syntax is approved, leaving only a handful of options, there is a huge variety of ways to tackle common problems if you dig a little deeper.
Throughout my Python work, I have learned of some interesting syntax options the language allows. Some of these styles are not widely used and even regarded as less “Pythonic” than their more conventional counterparts. I’ll let you be the judge and use them where applicable.
Let’s take a look.
1. Ternary operator with tuples
Normally, in Python you perform ternary assignments like this:
my_variable = 1 if <condition> else 2
Simple enough. You assign 1
if the <condition>
is true and 2
if it isn’t. But let’s look at a slightly different way of doing this:
my_variable = (2, 1)[condition]
In this example, we shorten the statement even more by using this neat tuple syntax. If the condition is true, the second element 1
is returned. If the condition is false, the first element 2
is returned.
Although this is a less clear way of performing the ternary assignment, it is quite compact. If you’re working in some dense, tuple-heavy areas of code, this could come in handy. Just remember to be explicit about variable naming and there shouldn’t be any confusion.
2. Multi-line strings with parentheses
There are a number of techniques for printing strings, concatenating strings, manipulating strings. You name it. Python can slice and dice with the best of them.
One thing I always find a need for is splitting up long string statements across multiple lines. One way to do this is by escaping the newline to fool the interpreter into thinking everything is one big line:
print(
"this is a " + \
"really long " + \
"string"
)