Назад к подготовке
ВопросСредняяpython-runtimeТехническое собеседование · Okko

Вопрос

How are arguments passed to functions in Python? What happens if a function mutates a list argument versus reassigning an immutable value?

Ответить самому

Сначала сформулируйте ответ как на собеседовании, затем откройте разбор и оцените себя.

Загрузка

Короткий ответ

Python passes object references by assignment. A function receives a new local name bound to the same object. Mutating a mutable object is visible outside; rebinding the local name is not.

Полный разбор

A precise way to say it is "call by object sharing" or "pass by assignment". The function parameter becomes a local name bound to the same object as the argument expression.

If the object is mutable, such as a list, an in-place mutation like append changes that shared object, so the caller observes the change. If the function reassigns the parameter name, it only changes the local binding. If the object is immutable, such as an int or tuple, operations that look like modification actually create a new object or fail, so the caller's original object is not modified.

This is neither C-style pass-by-value of the full object nor pass-by-reference where assignment to the parameter changes the caller's variable binding.

Теория

Names are bindings to objects. Mutability controls whether shared object state can be changed.

Типичные ошибки

  • Say mutable objects are passed by reference and immutable objects by value.
  • Confuse mutating an object with rebinding a local variable.

Как отвечать на собеседовании

  • Use a list append example and an integer reassignment example.
  • Avoid overloaded C++ terminology unless you define it carefully.