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

Using Gemini API in LangChain: Step-by-Step Tutorial

What is LangChain and Why Use It? LangChain  is an open-source framework that simplifies the use of  Large Language Models (LLMs)  like OpenAI, Gemini (Google), and others by adding structure, tools, and memory to help build real-world applications such as chatbots, assistants, agents, or AI-enhanced software. Why Use LangChain for LLM Projects? Chainable Components : Easily build pipelines combining prompts, LLMs, tools, and memory. Multi-Model Support : Work with Gemini, OpenAI, Anthropic, Hugging Face, etc. Built-in Templates : Manage prompts more effectively. Supports Multi-Turn Chat : Manage complex interactions with memory and roles. Tool and API Integration : Let the model interact with external APIs or functions. Let's Walk Through the Code: Gemini + LangChain I will break the code into  4 main parts , each showcasing different features of LangChain and Gemini API. Part 1: Basic Gemini API Call Using LangChain import os from dotenv import load_dotenv load_dot...

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 ...

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...