Skip to main content

Python-Day 3-Understanding Dynamic Typing & Mutable vs Immutable Types in Python

 Hey,

Here is the Day 3 updates of my Python learning journey! Today, I explored two essential concepts that make Python a flexible and powerful programming language: 

Dynamic Typing and Mutable vs Immutable Types

Let's dive deep into these topics!


Understanding Dynamic Typing in Python

Python is a dynamically typed language, meaning that variable types are determined at runtime. Unlike statically typed languages such as Java or C++, where you need to declare the type of a variable explicitly, Python allows you to assign any value to a variable without specifying its type.

Example of Dynamic Typing:

x = 10       # x is an integer
print(type(x))  # Output: <class 'int'>

x = "Hello"  # x is now a string
print(type(x))  # Output: <class 'str'>

x = [1, 2, 3]  # x is now a list
print(type(x))  # Output: <class 'list'>

Key Takeaways:

  • No need to declare variable types in Python.

  • The same variable can hold different types of data at different points in the program.

  • It makes Python more flexible but requires caution to avoid unexpected type errors.

Example of a potential issue with dynamic typing:

a = "10"  # String
a = a + 5  # This will cause a TypeError: can only concatenate str (not "int") to str

To fix this, we must ensure type consistency:

a = int("10")  # Convert string to integer
a = a + 5  #  Works fine, output: 15

Mutable vs Immutable Types in Python

In Python, every object belongs to one of two categories:

  1. Mutable Objects: Their values can be changed after creation.

  2. Immutable Objects: Their values cannot be changed once created.

 Mutable Objects (Can Be Modified)

Mutable objects allow modifications without changing their memory address.

Examples of Mutable Types:

  • Lists (list)

  • Dictionaries (dict)

  • Sets (set)

my_list = [1, 2, 3]
print(id(my_list))  # Memory address before modification

my_list.append(4)  # Modifying the list
print(my_list)  # Output: [1, 2, 3, 4]

print(id(my_list))  # Same memory address -> List is mutable

Immutable Objects (Cannot Be Modified)

Immutable objects do not allow modifications. If a change is needed, a new object is created with the updated value.

Examples of Immutable Types:

  • Integers (int)

  • Floats (float)

  • Strings (str)

  • Tuples (tuple)

my_tuple = (1, 2, 3)
print(id(my_tuple))  # Memory address before modification attempt

# my_tuple[0] = 100  ❌ This will cause an error: TypeError: 'tuple' object does not support item assignment

# Instead, we must create a new tuple
new_tuple = (100,) + my_tuple[1:]
print(new_tuple)  # Output: (100, 2, 3)
print(id(new_tuple))  # Different memory address -> New object created

Why Does This Matter?

  • Performance: Immutable types are more memory-efficient and can be used as dictionary keys and set elements.

  • Thread Safety: Immutable objects prevent accidental modifications in multi-threaded environments.

  • Function Arguments: Understanding mutability helps prevent unexpected behavior when passing objects to functions.


Summary of Today’s Learnings

ConceptExplanationExamples
Dynamic TypingPython assigns types dynamically at runtime.x = 10, x = "Hello"
Mutable TypesCan be modified in place.list, dict, set
Immutable TypesCannot be changed after creation.int, float, str, tuple

Mastering dynamic typing and mutability is crucial to writing efficient, bug-free Python programs. These concepts help in understanding memory management and data handling better. 

Next Steps: Explore how mutability affects function arguments and learn about deep vs shallow copying!

Comments