Member-only story
Python
7 Confusing Python Code Snippets and Their Explanation
Understand surprising Python features and avoid hidden pitfalls
Python is not necessarily always elegant and straightforward.
I’ve been using Python for almost a decade now, and sometimes I still find myself scratching my head at certain pieces of code.
This article will summarize the 7 most baffling Python code snippets I’ve ever encountered. The trickiest part is that all of them seem problematic, but some can still work and even logically make sense.
1. Are there comma-equal operators in Python?
I was 100% sure the following code would raise a syntax error when I met it:
x ,= range(1)
print(x)
However, it worked fine and printed 0.
But why? Is there a ,=
operator in Python?
After doing some research, I got it.
It is a valid assignment statement. It takes a tuple on the left and assigns each element of the tuple to the corresponding element on the right. In this case,
x
is the only element of the tuple and it gets assigned to 0.