4 ms·
You can do that if the parameter is a list: def change(l): l[1] = 'x' >>> foo = [1,2,3] >>> foo [1, 2, 3] >>> changel(foo) >>> foo [1, 'x', 3
by graemep 2y ago
You can do that if the parameter is a list:
def change(l):
l[1] = 'x'
>>> foo = [1,2,3]
>>> foo
[1, 2, 3]
>>> changel(foo)
>>> foo
[1, 'x', 3]
- pansa2 2y agoYou can't change which list `foo` refers to, though. Only the contents of that list. `foo` is a reference to a list, and that reference is passed by value.
- pjmlp 2y agoNow make foo point to another list, not change contents of the list foo points to. Passing by reference requires changing the variable itself, used on the call site.
- zahlman 2y agoThis does a fundamentally different thing with similar syntax. Assignment in Python is fundamentally a rebinding operation; slice assignment rebinds a reference internal to the object, whereas ordinary assignment rebinds the name. The classic test: in Python you cannot write a generic "swap function" - you could only possibly write a function to swap the internal states of the arguments, presuming them to be compatible.