Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is immutable in Python

Understanding Immutability in Python

When you're starting to learn programming, you'll come across the concept of 'immutability'. In simple terms, immutability refers to the idea that once an object is created, it cannot be changed. Think of it like a written contract; once it's signed, the terms can't be altered without creating a new contract.

In Python, some types of objects are immutable, which means once they are created, they cannot be modified. This is an important concept because it affects how you write code and how your programs behave.

The Basics of Immutable Types

Let's start with the basic immutable types in Python. These include:

  • Integers: Whole numbers like 1, 2, 3, etc.
  • Floats: Numbers with a decimal point, like 3.14, 2.718, etc.
  • Strings: Sequences of characters like "hello", "world".
  • Tuples: An ordered collection of items which can be of different types, like (1, "apple", 3.14).

Here's a simple code example to illustrate immutability with integers:

x = 10  # Assign the value 10 to the variable x
print(x)  # This will output: 10

x = x + 1  # Now we're not changing 10, but creating a new value (10 + 1) and assigning it back to x
print(x)  # This will output: 11

In the above example, we're not altering the number 10 itself. Instead, we're creating a new number by adding 1 to 10 and then storing that new number in the same variable, x.

Strings and Their Immutable Nature

Strings in Python are also immutable. This means that once a string is created, you can't change the individual characters within it.

Here's an example:

greeting = "hello"
print(greeting)  # Outputs: hello

# Let's try to change the first character to 'H'
# greeting[0] = "H"  # Uncommenting this line will cause an error because strings are immutable

If you try to run the commented-out line, Python will throw an error. To 'change' a string, you actually need to create a new one:

greeting = "hello"
greeting = "H" + greeting[1:]  # Create a new string and assign it to greeting
print(greeting)  # Outputs: Hello

Here, we've created a new string that starts with 'H' and then adds the rest of the original string from the second character onwards.

Tuples as Immutable Collections

Tuples are like lists in Python, but they're immutable. You can think of a tuple as a fixed set of elements. Once a tuple is created, you can't add, remove, or change its elements.

my_tuple = (1, 2, 3)
print(my_tuple)  # Outputs: (1, 2, 3)

# Let's try to change the second element to 4
# my_tuple[1] = 4  # Uncommenting this line will cause an error because tuples are immutable

To 'change' a tuple, you would need to create a new tuple entirely.

Why Does Immutability Matter?

Immutability might seem like a limitation, but it's actually a feature that can help you write safer and more predictable code. Here's why:

  • Predictability: Immutable objects can't change, which means you can rely on their value remaining the same throughout your program. This predictability makes your code easier to understand and debug.
  • Safety: Since immutable objects can't be changed, they are safe from accidental modifications, which could lead to bugs.
  • Concurrent Programming: In concurrent programming, where multiple threads are executing at the same time, immutability can prevent issues where two threads try to change the same object simultaneously.

The Contrast: Mutable Types

To fully appreciate immutability, it's helpful to understand its opposite: mutability. Mutable types in Python can be changed after they are created. The most common mutable types are:

  • Lists: Ordered collections of items, which can be of different types.
  • Dictionaries: Collections of key-value pairs.
  • Sets: Unordered collections of unique elements.

Here's an example with a list:

my_list = [1, 2, 3]
print(my_list)  # Outputs: [1, 2, 3]

# Let's change the second element to 4
my_list[1] = 4
print(my_list)  # Outputs: [1, 4, 3]

As you can see, we can directly change an element in a list because lists are mutable.

Intuition and Analogies

Think of immutable objects as your favorite book. Once it's printed and bound, you can't change the words on the pages (immutable). But you can always start a new book or make a photocopy and write notes on it (creating a new object).

In contrast, mutable objects are like a whiteboard. You can write on it, erase it, and modify it as needed.

When to Use Immutable Types

You might be wondering when you should use immutable types. The answer depends on the situation:

  • When you need to ensure that the value doesn't change: If you're dealing with important data that must remain constant, like configuration data, using an immutable type can be a good choice.
  • When you're working with concurrency: If your program is running multiple threads, using immutable types can prevent data from being corrupted by simultaneous modifications.

Conclusion

Understanding immutability in Python is a fundamental step in becoming a proficient programmer. It's a concept that, once grasped, provides clarity and reliability in your code. While immutable objects can seem restrictive at first, they offer a level of safety and predictability that can be invaluable in complex systems.

Imagine immutability as the North Star in the night sky. Just as the North Star remains constant and guides travelers, immutable objects serve as a steady and unchanging reference in your programs. Embrace the constancy of immutability, and you'll navigate the seas of code with confidence and precision. Remember, in the world of programming, some change is good, but sometimes stability is even better.