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 Fine-Tune LLaMA 3.2-1B-Instruct for Korean Instruction Tasks with LoRA and Hugging Face

LLaMA 3.2-1B-Instruct is a lightweight instruction-tuned language model released by Meta. It is designed to handle a wide range of instruction-based tasks with relatively low computational resources. Although the model was trained with multilingual capabilities, its performance on languages not included in its training set—such as Korean—is limited. This tutorial demonstrates how to fine-tune this open-source model on a Korean dataset using Hugging Face Transformers and PEFT (specifically LoRA), enabling it to better respond to Korean instructions. 1. Prerequisites Before running the example code below, ensure you have the following libraries installed: pip install torch transformers datasets peft accelerate mlflow huggingface_hub To use the LLaMA model or KoAlpaca datasets, you'll need a Hugging Face token. Additionally, you may need to handle potential CUDA Out-Of-Memory (OOM) errors. The following code takes care of both: from huggingface_hub import login login("y...

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

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