All courses › Programming with Python › Mutable objects and references
Mutable objects and references
Lists and dictionaries are mutable: when passed into a function, the function works on the same, shared list — changes are visible outside too. Numbers, strings and tuples are immutable and can never be changed afterwards, only replaced.
e.g.
list.appendSymbols
| the object passed to the function |
Example
def f(x): x.append(4)
a = [1, 2, 3]; f(a)
len(a) is now 4, because a and x point to the same list.
To keep the original unchanged, pass a copy:
Practise functions and data structures for free →
f(a.copy()).← String methods · Reading and writing files →
Part of Programming with Python: Functions and data structures.