You just said it yourself, why is it good practice?
Mostly, it's good practice because that's the standard way to do it (like that's how most code will be written). But in a lot of cases it's not necessary:
>>> x = 1, 2, 3
>>> x
(1, 2, 3)
>>> y = (1, 2, 3)
>>> y
(1, 2, 3)
>>> x == y
True
In simple code like this, it doesn't actually matter if you have the parentheses or not. But one thing to note is that tuples will always be printed out with them (as you can see in the example above). That's one reason that it's generally best to put them when defining a tuple, so that your input looks like the output you'd get. The other is because in some more complicated expressions, it actually matters if you have the parentheses or not. For example:
>>> 1, 2 + 3, 4
(1, 5, 4)
>>> (1, 2) + (3, 4)
(1, 2, 3, 4)
Addition is overloaded to concatenate tuples, that's what's going on in the second example. But addition also has a higher precedence, so when you're evaluating the above expressions,
2+3 is done first unless you use parentheses to make it go in the other order. It's the same as the difference between
1+2*3+4 => 11 and
(1+2)*(3+4) => 14.
I have found another example,
if not(a):
print ("a is false")
if not a:
print ("a is false")
Work exactly the same, and I'm not sure what putting the 'a' in parentheses does. I just want to make sure so that I can actually understand why something might not work
In this case, the parentheses don't do anything.
not isn't a function, otherwise you would need them. It's actually an operator, like
+, only it's unary so it only takes one argument. It's basically the same thing as using the other unary operator:
-. You can write
-5 or
-(5) and both will evaluate to the same thing. In this case, there's really no reason to have the parentheses there.
When you would want them is if a were a more complicated expression. For example:
>>> not True and False
False
>>> not (True and False)
True
Because
and has a lower precedence than
not, the first example should be read as
(not True) and False => False and False => False. The second forces the evaluation of
and first though, so you get
not (True and False) => not False => True. Granted, it's a really contrived example and it took me about 10 minutes to actually come up with one that works, but it does show that such examples are at least possible.
Note: You can see the entire precedence table in Section 5.15 on this page:
5. Expressions. The further an operator is down the table, the higher precedence it has (and the earlier it would get evaluated). Personally, I always forget what order
and /
or go in, so I'll generally over-parentheses there, but otherwise, it gets to be pretty intuitive.