Search⌘ K
AI Features

Mutating the Immutable!

Explore how Python handles immutable sequences and understand the impact of in-place mutations using operators like +=. Learn to recognize common behaviors and exceptions when working with immutable data types to improve your Python programming skills.

We'll cover the following...

This might seem trivial if you know how references work in Python.

Python 3.5
>>> some_tuple = ("A", "tuple", "with", "values")
>>> another_tuple = ([1, 2], [3, 4], [5, 6])
>>> some_tuple[2] = "change this"
TypeError: 'tuple' object does not support item assignment
>>> another_tuple[2].append(1000) #This throws no error
>>> another_tuple
([1, 2], [3, 4], [5, 6, 1000])
>>> another_tuple[2] += [99, 999]
TypeError: 'tuple' object does not support item assignment
>>> another_tuple
([1, 2], [3, 4], [5, 6, 1000, 99, 999])

Let’s try these in the terminal below.

Terminal 1
Terminal
Loading...

Explanatio ...


...