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.

f(x)⇒x changes permanently, if x is mutablef(x) \Rightarrow x \text{ changes permanently, if } x \text{ is mutable}e.g. list.append

Symbols

xxthe 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: f(a.copy()).
Practise functions and data structures for free →

← String methods · Reading and writing files →

Part of Programming with Python: Functions and data structures.