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

Understanding SentencePiece: A Language-Independent Tokenizer for AI Engineers

In the realm of Natural Language Processing (NLP), tokenization plays a pivotal role in preparing text data for machine learning models. Traditional tokenization methods often rely on language-specific rules and pre-tokenized inputs, which can be limiting when dealing with diverse languages and scripts. Enter SentencePiece—a language-independent tokenizer and detokenizer designed to address these challenges and streamline the preprocessing pipeline for neural text processing systems. What is SentencePiece? SentencePiece is an open-source tokenizer and detokenizer developed by Google, tailored for neural-based text processing tasks such as Neural Machine Translation (NMT). Unlike conventional tokenizers that depend on whitespace and language-specific rules, SentencePiece treats the input text as a raw byte sequence, enabling it to process languages without explicit word boundaries, such as Japanese, Chinese, and Korean. This approach allows SentencePiece to train subword models di...

Mastering the Byte Pair Encoding (BPE) Tokenizer for NLP and LLMs

Byte Pair Encoding (BPE) is one of the most important and widely adopted subword tokenization algorithms in modern Natural Language Processing (NLP), especially in training Large Language Models (LLMs) like GPT. This guide provides a deep technical dive into how BPE works, compares it with other tokenizers like WordPiece and SentencePiece, and explains its practical implementation with Python code. This article is optimized for AI engineers building real-world models and systems. 1. What is Byte Pair Encoding? BPE was originally introduced as a data compression algorithm by Gage in 1994. It replaces the most frequent pair of bytes in a sequence with a single, unused byte. In 2015, Sennrich et al. adapted BPE for NLP to address the out-of-vocabulary (OOV) problem in neural machine translation. Instead of working with full words, BPE decomposes them into subword units that can be recombined to represent rare or unseen words. 2. Why Tokenization Matters in LLMs Tokenization is th...

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