Understanding Operators, Strings, and Mutable vs Immutable in Python — Explained with Memory Diagrams 🧠


Understanding Operators, Strings & Mutable vs Immutable in Python — With Diagrams!

Python is famous for being “simple,” but under the hood? There’s a lot happening with how it handles data, especially when it comes to operators, strings, and object mutability.

Today, let’s decode these topics together — with practical examples and easy-to-visualize diagrams.


FLUX

🔢 Operators in Python — The Building Blocks

Operators are the core tools for manipulating data. Here’s a quick snapshot:

TypeExamplePurpose
Arithmetic+, -, *, /Basic math operations.
Comparison==, !=, >, <Compare values.
Logicaland, or, notCombine conditions.
Assignment=, +=, -=Assign/change values.
Bitwise&, `, ^`
Membershipin, not inCheck for existence in sequences.
Identityis, is notCompare object memory addresses.

Other Useful Operators in Python

OperatorDescriptionExampleResult
+Addition10 + 515
-Subtraction10 - 55
*Multiplication10 * 550
/Division10 / 52.0
%Modulus10 % 31
**Exponentiation2 ** 38
//Floor Division10 // 33

FLUX

Mutable vs Immutable Objects in Python

What Does Mutable Mean?

  • Mutable objects can be changed after creation.

  • Immutable objects cannot be changed after creation; any "modification" creates a new object.

Common Examples

TypeMutable?Examples
String❌ Immutable"hello", "123"
List✅ Mutable[1, 2, 3]
Tuple❌ Immutable(1, 2, 3)
Dictionary✅ Mutable{"a": 1}
Set✅ Mutable{1, 2, 3}
Integer❌ Immutable42

Immutable Example: Strings

When you modify a string, Python creates a new object in memory.


🧵 Deep Dive: The Difference Between is and ==

One of the most common beginner traps is mixing up is and ==.
They sound similar, but behave very differently!

OperatorPurposeExampleResult
==Checks if values are equal"hello" == "hello"True
isChecks if identity is same (memory)"hello" is "hello"⚠️ True (sometimes)

💡 Why is Can Be Tricky

a = "hello"
b = "hello"
print(a is b)  # True (due to string interning)

x = 256
y = 256
print(x is y)  # True (small integers are cached)

p = 257
q = 257
print(p is q)  # False (new object for larger ints)

Memory Tip: Visualizing id()

id() gives you the actual memory address (unique identifier) for an object.

pythonCopyEdita = [1, 2, 3]
b = a

print(id(a))  # 139986175432800
print(id(b))  # 139986175432800

✅ Both a and b point to the same list in memory.

But if you reassign a:

pythonCopyEdita = [4, 5, 6]
print(id(a))  # New address

🔥 Pro Tip: Why Immutability is Powerful

Immutable objects:

  • Are hashable (can be used as dictionary keys).

  • Are thread-safe.

  • Help Python optimize memory (e.g., via interning).

For example:

pythonCopyEditmy_dict = {
    ("John", "Doe"): 123,
    ("Jane", "Smith"): 456
}

Tuples are immutable, so Python can safely use them as keys.

If you tried the same with a list, you'd hit an error:

pythonCopyEditmy_bad_dict = {
    ["John", "Doe"]: 123   # ❌ TypeError: unhashable type: 'list'
}

💡 Analogy: Mutable vs Immutable as People

Imagine two friends, Alice and Bob.

BehaviorMutable ExampleImmutable Example
Change outfitAlice wears new clothes dailyBob tattooed his outfit on.
Memory referenceSame identityNeeds cloning for each change

In Python terms:

  • Alice = mutable (list, dict)

  • Bob = immutable (str, tuple)


Memory Management in Python - Honeybadger Developer Blog

💡 Strings & Operator Magic

Strings are immutable text sequences in Python. Once created, their content can’t be changed.

a = "Hello"
b = "Hello"
print(a == b)   # True - Same values
print(a is b)   # True or False - Same memory? Depends!
0
Subscribe to my newsletter

Read articles from Mrityunjay Agarwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Mrityunjay Agarwal
Mrityunjay Agarwal