Python Mutable and Immutable Variables: Key Differences Explained

Based on the mutability, Python variables can be categorized into two main types mutable and immutable. Understanding the difference between these two types is crucial for writing efficient and bug-free Python code.

What is Mutability?

In Python Mutability refers to whether an object’s value can be changed after it’s created. Let us assume that you have a magic box that holds a number. If the box is mutable, you can change the number inside it anytime. But if it’s immutable, once you put a number in the box, you can’t change it; you’d have to get a new box with a different number.

let us understand it in depth

For example, think of a list as a mutable object. You can add, remove, or change items in the list anytime you want. But if you think of a tuple as an immutable object, once you create it with some items, you can’t change those items; you’d have to create a new tuple with different items.

Now that it is clear what is mutability, let us understand one by one about immutable and mutable variables. Stay with me don’t miss this part out !

Immutable Variables:

Immutable variables are those whose values cannot be changed after they are created. In Python, the following data types are immutable:

  • int
  • float
  • complex
  • str
  • tuple

Example:

Imagine you have a post-it note (variable) with the number 5 written on it. This note is immutable, so once you write 5 on it, you can’t change it directly. If you want to change the value, you need to create a new post-it note with a different number.

# Creating an immutable variable
x = 5  # x is a post-it note with 5 written on it

# Attempting to change the value of the immutable variable
# This will actually create a new post-it note with the new value
x = 10  # Now x is a new post-it note with 10 written on it

In this example, the value of x cannot be changed directly; instead, a new post-it note with a new value is created. This behavior is similar to how immutable variables work in Python.

Let us take another example:

num = 10
print("Original num:", num)

# Attempting to change the value of num
num = 20
print("Updated num:", num)

In the above example, num is an immutable variable of type int. The moment we assign a new value to num, it actually creates a new object in memory with the value 20, while the original object with the value 10 remains unchanged. This behavior is consistent across all immutable data types in Python.

Let us now take an example of a tuple

# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)

# Attempting to change an element of the tuple (this will raise an error)
# my_tuple[0] = 10  # This will raise an error because tuples are immutable

# Reassigning the tuple variable to a new tuple with a different value
my_tuple = (10, 2, 3, 4, 5)  # This is allowed because it creates a new tuple

print(my_tuple)  # Output: (10, 2, 3, 4, 5)

In the above example, if we try to change an element of the tuple directly (my_tuple[0] = 10) it will raise an error because tuples are immutable. Instead, we can reassign the variable my_tuple to a new tuple, as shown in the second part of the code, to effectively “change” the value of the tuple.

Some more examples

Immutable Variables (Examples):

Integers: Once you define an integer variable, its value cannot be changed. For example

age = 30

Strings: Strings are immutable. If you create a string variable, its value cannot be modified. For example:

name = "Alice"

Mutable Variables (Examples):

Lists: Lists can be modified after creation. You can add, remove, or change elements in a list. For example:

shopping_list = ["apple", "banana", "orange"]
shopping_list.append("pear")  # This modifies the list

Dictionaries: Dictionaries can also be modified. You can add, remove, or change key-value pairs. For example:

person = {"name": "Bob", "age": 25}
person["age"] = 26  # This modifies the dictionary

In these examples, the immutable variables (integers and strings) cannot be changed once they are created, while the mutable variables (lists and dictionaries) can be modified after creation.

Mutable Variables:

On the other hand, Mutable variables, are those whose values can be changed after they are created. In Python, the following data types are mutable:

  • list
  • set
  • dict

Let us see an example

Mutable variables in Python can be exemplified with a list. Lists can be modified after creation, making them mutable. Here’s an example in a real-life context, managing a shopping list:

# Creating a shopping list
shopping_list = ["apples", "bananas", "bread", "milk"]

# Adding an item to the shopping list
shopping_list.append("eggs")

# Removing an item from the shopping list
shopping_list.remove("bread")

# Changing the quantity of an item in the list
shopping_list[1] = "2 bananas"  # Change "bananas" to "2 bananas"

print(shopping_list)

in the above code, shopping_list is a mutable variable. We can modify it by adding items (append), removing items (remove), or changing items (assignment). This behavior is characteristic of mutable objects in Python.

Another example

my_list = [1, 2, 3]
print("Original list:", my_list)

# Modifying the list
my_list.append(4)
print("Modified list:", my_list)

Here in the above code, my_list is a mutable variable of type list. When we append 4 to my_list, the original list is modified in-place, and no new object is created in memory.

Key Difference

AspectImmutable ObjectsMutable Objects
Memory EfficiencyMore memory-efficient due to reuse of objectsLess memory-efficient due to need for new objects
ModificationCannot be modified, operations create new objectsCan be modified in-place
HashabilityHashable, can be used as keys in dictionariesNot hashable, cannot be used as keys in dictionaries
ExamplesIntegers, floats, strings, tuplesLists, sets, dictionaries

Conclusion,

Understanding the difference between mutable and immutable variables is essential for writing efficient Python code and avoiding unexpected behavior, especially when dealing with data structures and functions that rely on mutability.

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>