+ 4
When should you put parenthesis on tuples, and when shouldn't you?
I was just thinking about it, because I haven't questioned it before. If you do: my_tuple = "example", "example2"... and so on, it is the same as: my_tuple = ("example", "example2"...) What is the difference? Is the former faster in big programs?
1 Odpowiedź
+ 10
The parentheses are necessary when we need nested tuples, or tuples with 0 or 1 element, or in some cases where we write a tuple as a part of a larger expression
a = (1, (2, 3), 4)
b = ()
c = (1,)
d = (1, 2) + (3, 4)
But when there's no ambiguity, I don't think it matters (though I haven't done a speed test). Personally, I don't use parentheses when I'm doing sequence unpacking, like
a, b = b, a
for i, n in enumerate(my_list):
But in other situations, when I expect the elements of the tuple to stay together, I do use parentheses, mostly as visual indicators. For example, when I'm using a tuple to represent the coordinates of a point or a vector, as they are normally written using parentheses.