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

Popular posts from this blog

Python - Day 1 – Starting My Python Learning Journey!

Hello 👋 Today marks the first day of my Python learning journey, and I’m excited to share my progress with you. It’s a fresh start, and I’ve already learned some cool basics that have me looking forward to more! Here’s a quick breakdown of what I’ve learned today: What is Python? I got familiar with Python as a high-level, interpreted programming language. It’s known for being easy to learn, clean, and readable, which is perfect for beginners like me! I learned that Python can be used for web development, data analysis, AI, ML, automation, and much more. The possibilities are endless! Hello World – My First Program The first thing I did was write my very first Python program: the classic "Hello World". It was such a simple but satisfying moment! Here's what it looked like: print("Hello, World!") It was so exciting to see my code run and display something on the screen. It might seem like a tiny step, but it felt like a big win to me! Time Spent : ...

Python-Day 2–Diving Deeper into Python: Variables, Operations, and More!

  Hey! I’m back with my Day 2 update on my Python learning journey. Today was all about getting hands-on with variables, data types, and basic operations. I spent decent 3 hours and to write blog additional 1 hour to summarize my learning. bit hectic however its being weekend i thought of spend more time today on basics to get along with programming so that i can invest less time during weekdays. It feels so satisfying to be writing more complex code already, even though I’m still just scratching the surface! Here’s a quick rundown of what I’ve learned: Firstly, Downloaded and configured the VSCode on my windows Laptop. and executed Hello World command. then moved ahead with learning basic Syntax and Structure ( print(), comments, indentation) Variables & Data Types I learned how to store information in variables and use different data types like strings, integers, floats, and booleans. For example, I learned how to assign values like name = "Sri Ram" and age = ...