Вопрос
In Python, what actually makes a tuple: parentheses or comma? Give examples.
Сначала проговорите ответ вслух или тезисами.
Формулы, план решения, риски и примеры.
Откройте разбор только после своей попытки.
Показать разбор
Короткий ответ
The comma creates the tuple, not the parentheses. (1) is just 1, while (1,) and 1, are one-element tuples.
Подробный разбор
In Python, parentheses are often only grouping syntax. The comma is what creates a tuple literal. For example, (1) evaluates to the integer 1, but (1,) evaluates to a one-element tuple. Similarly, 1, is also a tuple.
Parentheses are still commonly used for readability and are required in some contexts to avoid ambiguity, such as function calls or nested expressions. But the semantic tuple marker is the comma-separated sequence.
This matters in interviews because one-element tuple syntax is a common source of bugs in function arguments, return values and unpacking. Always add the trailing comma when you mean a singleton tuple.