Skip to main content

Mutable vs Immutable Data Types in Python Explained

When learning Python, one of the most important concepts to understand is the difference between mutable and immutable data types. To explain this concept, I'm going to break it down step-by-step with examples and visuals!


1. What Do "Mutable" and "Immutable" Mean?

  • Mutable means: You can change the object after it’s created.
  • Immutable means: Once the object is created, it cannot be changed.

Think of it like this:

TypeReal-life Analogy
MutableA whiteboard: you can erase and write again
ImmutableA printed photo: once printed, you can’t change it


2. Immutable Data Types in Python

These are data types that cannot be changed after they are created.

Examples of Immutable Types:

  • int
  • float
  • bool
  • str
  • tuple
  • frozenset

Example 1: Integers (int)

a = 5
print(id(a))  # memory address of a

a = a + 1
print(a)      # 6
print(id(a))  # different memory address!

Even though just added 1 to a, Python created a new object in memory for the result.

**Key point: Integers can't be changed in-place. When you "change" them, you're actually creating a new integer object.


Example 2: Strings (str)

s = "hello"
print(id(s))

s = s + " world"
print(s)        # "hello world"
print(id(s))    # memory address has changed

Even though it looks like we modified the string, Python made a brand new one.

3. Mutable Data Types in Python

These are data types that can be changed without creating a new object.

Examples of Mutable Types:

  • list
  • dict
  • set
  • bytearray
  • Custom objects (most of them)

Example 3: Lists (list)

my_list = [1, 2, 3]
print(id(my_list))

my_list.append(4)
print(my_list)     # [1, 2, 3, 4]
print(id(my_list)) # Same memory address!

Added an item to the list and the memory address did not change. That means the same object was updated in-place.


Example 4: Dictionaries (dict)

my_dict = {"name": "Alice"}
print(id(my_dict))

my_dict["age"] = 30
print(my_dict)      # {'name': 'Alice', 'age': 30}
print(id(my_dict))  # Same memory address

Just like lists, dictionaries can also be changed in-place.

4. Visual Illustration

Here’s a simple diagram to help visualize this:

Local variable is immutable but list is mutable

5. Why Does This Matter?

Understanding mutability helps you:

  • Avoid unexpected bugs when passing data to functions.
  • Use Python's data types more effectively.
  • Understand how Python handles memory and performance.

Comments

Popular

How to Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings

How to Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings Efficient storage and retrieval of vector databases is foundational for building intelligent retrieval-augmented generation (RAG) systems using large language models (LLMs). In this guide, we’ll walk through a professional-grade Python implementation that utilizes LangChain with FAISS and Google Gemini Embeddings to store document embeddings and retrieve similar information. This setup is highly suitable for advanced machine learning (ML) and deep learning (DL) engineers who work with semantic search and retrieval pipelines. Why Vector Databases Matter in LLM Applications Traditional keyword-based search systems fall short when it comes to understanding semantic meaning. Vector databases store high-dimensional embeddings of text data, allowing for approximate nearest-neighbor (ANN) searches based on semantic similarity. These capabilities are critical in applications like: Question Ans...

Building an MCP Agent with UV, Python & mcp-use

Model Context Protocol (MCP) is an open protocol designed to enable AI agents to interact with external tools and data in a standardized way. MCP is composed of three components: server , client , and host . MCP host The MCP host acts as the interface between the user and the agent   (such as Claude Desktop or IDE) and plays the role of connecting to external tools or data through MCP clients and servers. Previously, Anthropic’s Claude Desktop was introduced as a host, but it required a separate desktop app, license, and API key management, leading to dependency on the Claude ecosystem.   mcp-use is an open-source Python/Node package that connects LangChain LLMs (e.g., GPT-4, Claude, Groq) to MCP servers in just six lines of code, eliminating dependencies and supporting multi-server and multi-model setups. MCP Client The MCP client manages the MCP protocol within the host and is responsible for connecting to MCP servers that provide the necessary functions for the ...

RF-DETR: Overcoming the Limitations of DETR in Object Detection

RF-DETR (Region-Focused DETR), proposed in April 2025, is an advanced object detection architecture designed to overcome fundamental drawbacks of the original DETR (DEtection TRansformer) . In this technical article, we explore RF-DETR's contributions, architecture, and how it compares with both DETR and the improved model D-FINE . We also provide experimental benchmarks and discuss its real-world applicability. RF-DETR Architecture diagram for object detection Limitations of DETR DETR revolutionized object detection by leveraging the Transformer architecture, enabling end-to-end learning without anchor boxes or NMS (Non-Maximum Suppression). However, DETR has notable limitations: Slow convergence, requiring heavy data augmentation and long training schedules Degraded performance on low-resolution objects and complex scenes Lack of locality due to global self-attention mechanisms Key Innovations in RF-DETR RF-DETR intr...