When should you put parenthesis on tuples, and when shouldn't you? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

10th Nov 2018, 1:21 AM
DrChicken24
DrChicken24 - avatar
1 Answer
+ 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.
10th Nov 2018, 2:20 AM
Kishalaya Saha
Kishalaya Saha - avatar