Назад к подготовке
ВопросЛегкаяpython-runtimeСкрининг · WinStar

Вопрос

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.