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

"Welcome to My AI, Python, and ML Learning Journey!"

Hello, and welcome to my blog! 🎉 This is where I’ll be sharing my personal journey as I dive into the world of Python, Artificial Intelligence, and Machine Learning. Whether you’re a beginner like me, an experienced developer, or just curious about the exciting possibilities in these fields, I hope you’ll find something useful and inspiring here! I started this blog because I’ve always been fascinated by technology and the endless potential of AI. As I take my first steps into the world of programming and machine learning, I wanted to document my learning process, the challenges I encounter, and the successes I celebrate along the way. In this space, I’ll be exploring: Python: From the basics to more advanced topics, I’ll be diving deep into the Python programming language and how it connects to data science, AI, and ML. AI & ML: I’ll be tackling machine learning algorithms, exploring different models, and applying them to real-world problems. Projects and Tutorials: As I work on ...

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 : ...