Concept:
In Python, objects are classified as
mutable or
immutable depending on whether their values can be changed after creation. This property determines how data can be modified and managed in a Python program.
1. Mutable Objects:
A
mutable object is an object whose value or contents can be modified after it is created. Changes can be made without creating a new object.
Characteristics:
- The object's value can be changed after creation.
- Memory location remains the same after modification.
- Supports operations like adding, removing, or updating elements.
Examples of Mutable Objects:
Example:
\[
\texttt{my_list = [1,2,3]}
\]
\[
\texttt{my_list.append(4)}
\]
Here the list changes to \texttt{[1,2,3,4]} without creating a new object.
2. Immutable Objects:
An
immutable object is an object whose value cannot be changed after it is created. Any modification results in the creation of a new object.
Characteristics:
- Value cannot be modified after creation.
- Any change creates a new object in memory.
- Provides safer data handling and prevents accidental changes.
Examples of Immutable Objects:
Example:
\[
\texttt{x = 10}
\]
\[
\texttt{x = x + 5}
\]
Here a new object with value \texttt{15} is created.
Key Differences Between Mutable and Immutable Objects:
\[
\begin{array}{|c|c|c|}
\hline
Feature &
Mutable &
Immutable
\hline
Modification & Can be modified & Cannot be modified
\hline
Memory & Same object remains & New object created
\hline
Examples & List, Dictionary, Set & Integer, String, Tuple
\hline
\end{array}
\]