Sometimes you run across something in Python that looks like it should generate a syntax error but doesn’t. Here’s a monstrosity I ran into this morning.
Tuples in Python
I’ve always found tuples and tuple unpacking in Python to behave more than a little strangely.
For example, it’s a pretty common accident to include an extra comma and find out that rather than
and as it turns out, this is a perfectly reasonable way to create tuples! parentheses are optional.
but then of course when you explicitly try to create a tuple with one element
I guess that’s what you should expect, because the point of parentheses in Python is just order of operations and grouping multiline statements. So, technically, the correct way to make a tuple is the first one, and the fact that the parentheses are there in the
__str__ representation is just for our fragile eyes.
Unpacking tuples is another syntax lots of people might have seen but not have explored.
For those who aren’t familiar, tuple unpacking basically allows you to do multiple assignments in one expression as long as the number of variables matches the number of items, and it actually works for all iterables.
The most basic example:
but there’s also the convention of using
_ to drop items if you only want one
and that underscore is actually a variable, it’s just convention for “not needed.” You do need something there though, cause if you do
wait. it doesn’t complain that it’s a syntax error?
and as you may know, whitespace in some cases in Python can be ignored:
[10, 11, 12] == [10,11,12]
which leads us to this monstrosity