top

Search

Python Tutorial

.

UpGrad

Python Tutorial

Mutable and Immutable in Python

Introduction

Understanding the concepts of mutability and immutability, specifically within the context of Mutable and Immutable in Python, is critical in the world of Python programming. These terms refer to how objects behave when they are modified. The ability or inability of an object to be changed in place has significant implications for programming efficiency and data integrity. In this article, we'll delve into the fascinating world of mutable and immutable objects, investigating their properties, use cases, and impact on Python code. Whether you're a new or experienced developer, understanding these concepts will help you write more efficient and robust Python programs.

Overview

Objects are categorized as Mutable and Immutable in Python based on whether their values can be changed after creation. Mutable objects can be modified in place, while immutable objects cannot be altered once they are created. Understanding the distinction between these two types of objects is essential for writing efficient and bug-free code.

This article introduces Mutable and Immutable in Python objects, showcases their behaviors through examples, and discusses their impact on memory management and data integrity. Whether you're a novice programmer or a seasoned developer, grasping the concepts enhances your proficiency in Python programming.

What are Mutable Objects?

Mutable objects in Python are those whose values can be changed after they are created. This means that you can modify the content of a mutable object without creating a new object. Changes made to a mutable object are reflected in place, and any variable referencing that object will see the modifications. Mutable objects play a significant role in data manipulation and are widely used in various programming scenarios.

Examples of Mutable Objects

Lists

One of the most common examples of mutable objects in Python is a list. Lists allow you to add, remove, or modify elements without the need to create a new list. Here's an illustration:

Output:

As you can see, the code changes the second element (index 1) of the list from 2 to 99, resulting in the modified list '[1, 99, 3]'.

Dictionaries

Dictionaries are another example of mutable objects. You can add, update, or remove key-value pairs without creating a new dictionary:

Output:

As you can see, the code changes the value associated with the "age" key from 30 to 31, resulting in the updated dictionary.

Sets

Sets are also mutable objects that allow you to add or remove elements:

Output:

This creates a set containing the elements 1, 2, and 3, and then adds the element 4 to the set, resulting in the updated set '{1, 2, 3, 4}'.

Custom Objects

When you create your own classes, you can design them to be mutable. This means you can define methods that modify the internal attributes of instances of your class.

In this case, the Person class's age attribute is mutable. You can modify it directly, which demonstrates the mutable behaviour of custom objects.

Output:

Here, you create a 'Person' instance with the name "Bob" and age 25. Then, you modify the age attribute of the 'person' object from 25 to 26, resulting in the modified age value being printed.

What are Immutable Data Types?

Immutable data types in Python are those whose values cannot be changed after they are created. Once an immutable object is created, its content remains fixed throughout its lifetime. Any attempt to modify an immutable object will result in the creation of a new object with the modified value. Immutable objects play a significant role in ensuring data integrity and are widely used for scenarios where the value should not be altered.

Examples of Immutable Data Types

Strings
Strings are perhaps the most common example of immutable in Python. Once a string is created, its characters cannot be changed individually:

Output:

In this, you start with the string "Hello" stored in the 'my_string' variable. When you concatenate it with " World", you create a new string "Hello World", which is stored in the 'new_string' variable. The original string in 'my_string' remains unchanged.

Tuples
Tuples are another example of immutable data types. Once a tuple is created, its elements cannot be modified:

Output:

Here, you start with the tuple '(1, 2, 3)' stored in the 'my_tuple' variable. When you concatenate it with '(4,)', you create a new tuple '(1, 2, 3, 4)', which is stored in the 'new_tuple' variable. The original tuple in 'my_tuple' remains unchanged because tuples are immutable in Python.

Numbers
Numbers, including integers, floats, and complex numbers, are also immutable:

Output:

Here, you start with the integer '5' stored in the 'my_int' variable. When you add '1' to it, you create a new integer '6', which is stored in the 'new_int' variable. The original integer in 'my_int' remains unchanged because integers are immutable in Python.

Frozen Sets
Frozen sets are sets that are also immutable:

Output:

Are Lists Mutable or Immutable in Python?

Lists are mutable objects in Python. This means that you can modify the contents of a list after it's created without creating a new list. This mutability makes lists a versatile and powerful data structure for various programming tasks.

Modifying Lists In-Place
Let's explore how lists' mutability works with some examples:

Output:

In this example, the second element of the list is modified from 2 to 99 using indexing. The change is directly reflected in the original list, showcasing its mutability.

Adding and Removing Elements
Lists' mutability allows for dynamic changes, including adding and removing elements:

Output:

Here:
1. 'my_list.append(5)' adds the element 5 to the end of the list, resulting in '[1, 99, 3, 4, 5]'.

2. 'my_list.remove(3)' removes the first occurrence of the element 3 from the list, resulting in '[1, 99, 4, 5]'.

The append() method adds an element to the end of the list, while the remove() method removes the specified value from the list.

Extending Lists
You can also extend a list by adding elements from another iterable:

The extend() method modifies the list by adding elements from the given iterable.

Output:

In this, 'my_list.extend(extension)' adds the elements from the 'extension' list (which is '[6, 7, 8]') to the end of 'my_list', resulting in '[1, 99, 4, 5, 6, 7, 8]'.

Reordering Elements
Lists can be reordered using methods like sort() and reverse():

Both the sort() and reverse() methods modify the list in place.

Output:

Here:

1. 'my_list.sort()' sorts the elements of 'my_list' in ascending order.

2. 'my_list.reverse()' reverses the order of elements in 'my_list', resulting in the reversed list '[99, 8, 7, 6, 5, 4, 1]'.

What are Immutable Objects?

In Python, immutable objects are those whose values cannot be changed after they are created. Once an immutable object is instantiated, its content remains constant throughout its lifetime. This characteristic has significant implications for data integrity and program behavior. Let's explore the concept of immutable objects with illustrative examples.

Examples of Immutable Objects

1. Strings
Strings are perhaps the most straightforward example of immutable objects. Once a string is created, you cannot modify its characters directly.

In this example, concatenating " World" to ‘my_string’ creates a new string ‘new_string’, leaving the original string unaltered.

2. Tuples
Tuples are ordered collections that cannot be modified after creation. You cannot change, add, or remove elements from a tuple directly.

Concatenating a new element to ‘my_tuple’ creates a new tuple ‘new_tuple’, preserving the immutability of the original tuple.

3. Numbers
Numeric types like integers and floats are immutable. Any operation that appears to modify a number actually creates a new number.

Here, adding 1 to ‘my_int’ produces a new integer, ‘new_int’, while ‘my_int’ remains unchanged.

4. Frozen Sets
Frozen sets are sets that cannot be modified after creation. They're essentially immutable sets.

Difference Between Mutable and Immutable in Python in Tabular Form

Aspect

Mutable Objects

Immutable Objects

Definition

Objects whose values can be changed

Objects whose values cannot be changed

Example

Lists, dictionaries, sets

Numbers (int, float), strings, tuples

Modification in Place

Can be modified in place using methods

Cannot be modified; create a new object with changes

Memory efficiency

May consume more memory due to changes

Typically memory-efficient as new objects aren't created for changes

Hashable

Not hashable (cannot be used as keys in dictionaries or elements in sets)

Hashable (can be used as keys in dictionaries and elements in sets)

Examples

my_list = [1, 2, 3]<br>my_list.append(4)

my_string = "hello"<br>my_string.upper()

Use cases

Suitable for dynamic data where values need to change frequently

Suitable for data that should remain constant; useful for keys in dictionaries and hash-based data structures

Performance impact

May have a performance impact in scenarios involving large-scale data manipulation

Generally has less impact on performance due to immutability

Assignment

Assigning a mutable object to a new variable creates a reference to the same object

Assigning an immutable object to a new variable creates a new independent object

Common methods

append(), extend(), pop(), remove()

upper(), lower(), replace(), join()

The Python ‘id()’ Function

Python's 'id()' function provides a unique identifier (memory address) for objects, helping you distinguish between shared or distinct objects in memory. This aids in object behavior and memory management. Explore 'id()' with examples.

Basic Usage of 'id()'
Here's the basic syntax of the 'id()' function:

'object': The Python object for which you want to retrieve the identity.

Example: Identity of Different Data Types


In this example, the 'id()' function returns the memory address of the variables 'num', 'word', and 'my_list'.

Output:

The actual memory addresses (represented as '<some_memory_address>') will vary depending on your specific Python environment and system. Each variable will have its own unique memory address.

Comparing Identities
You can use the 'id()' function to compare the identities of different variables:

The 'is' operator checks whether two variables reference the same object. In this case, since integers are immutable and small integers are cached by Python, both 'num1' and 'num2' reference the same object with the value 42.

In Python, small integer objects (typically in the range of -5 to 256) are cached and reused, so when you create two integer variables with the same value within this range, they often refer to the same object in memory. Here's what the output should be:

Both 'num1' and 'num2' will have the same memory address ('<same_memory_address_as_num1>'), and the 'num1 is num2' comparison will return 'True', indicating that they refer to the same object in memory. This behaviour is due to integer caching optimization in Python.

Modifying Objects and Identity
Mutable objects can change their contents, but their identity remains constant:

Here, the identity of ‘my_list’ remains the same even after appending an element. The object itself is modified, but its memory location doesn't change.

You first print the identity (memory address) of the 'my_list' and then append an element before printing its identity again. Here's what the output should be:

The memory addresses ('<some_memory_address>') will depend on your specific Python environment and system. However, the critical point to note is that after appending an element to the list, the identity of 'my_list' remains the same. This is because you are modifying the same list object in memory rather than creating a new list.

Immutability and Identity
Immutable objects always have the same identity because their values cannot change:

Both 'word1' and 'word2' reference the same string object "hello" in memory because strings are immutable.

In Python, string interning is a process where the Python interpreter caches and reuses certain string objects with the same value to save memory. For small string literals like "hello", Python typically interns them, which means that multiple variables containing the same string literal will often refer to the same string object in memory. Here's what the output should be:

Both 'word1' and 'word2' will have the same memory address ('<same_memory_address_as_word1>'), and the 'word1 is word2' comparison will return 'True', indicating that they refer to the same string object in memory. This behaviour is due to string interning optimization in Python. However, please note that this behaviour may not apply to all string objects, especially those created dynamically or with non-literal values.

Using id() for Debugging
The id() function can be helpful for debugging and understanding how objects are created and shared in memory. It allows you to verify whether objects are being reused or duplicated.

The id() function provides a powerful tool for examining object identity and memory behaviour in Python. By using it, you can gain insights into how Python manages memory and references, making it a valuable asset for both beginners and experienced developers.

Conclusion

The concepts of mutability and immutability shape how data is stored, accessed, and manipulated in Python. Understanding the distinctions between mutable and immutable objects enables you to write code that is efficient, predictable, and less likely to exhibit unexpected behaviour. By understanding these fundamental concepts, you will be able to make informed design decisions, write cleaner code, and confidently navigate the complex landscape of Python programming.

FAQs

1. What are the implications of mutability on memory usage in Python?
Mutable objects may consume more memory due to modifications. Immutable objects, on the other hand, are typically more memory-efficient.

2. Why is the distinction between mutable and immutable objects important in Python?
Understanding the difference between mutable and immutable objects is crucial for data manipulation, memory efficiency, and program behavior. Proper handling of mutable objects is necessary to prevent unintended side effects, while immutable objects provide data consistency and predictability.

3. What are mutable data types in Python?

Mutable data types in Python are data structures that allow you to change their values after creation. This means you can add, remove, or modify elements within these data types.

Leave a Reply

Your email address will not be published. Required fields are marked *