Modifiable (Changeable) with Python

Modifiable (Changeable)

Concept of Mutability

In Python, an object is considered mutable if its state or content can be modified after it is created. Dictionaries are mutable data structures, meaning you can change their content without creating a new dictionary object.

Modifying Dictionaries

Adding Elements

You can add new key-value pairs to a dictionary by assigning a value to a new key.

Example: 

d = {
    "name": "Alice",
    "age": 30
}
# Add a new key-value pair
d["city"] = "Paris"
print(d)  # Outputs {'name': 'Alice', 'age': 30, 'city': 'Paris'}

Modifying Existing Elements

You can change the value associated with an existing key by reassigning a new value to that key.

Example: 

d = {
    "name": "Alice",
    "age": 30
}
# Modify an existing value
d["age"] = 31
print(d)  # Outputs {'name': 'Alice', 'age': 31'}

Removing Elements

You can remove elements from a dictionary using several methods:

  • Using pop(): Removes the key-value pair specified by the key and returns the associated value.
  • Using popitem(): Removes and returns the last key-value pair inserted (available since Python 3.7).
  • Using del: Deletes the key-value pair specified by the key.

Example: 

d = {
    "name": "Alice",
    "age": 30,
    "city": "Paris"
}
# Remove with pop()
value = d.pop("city")
print(value)  # Outputs 'Paris'
print(d)      # Outputs {'name': 'Alice', 'age': 30}
# Remove with popitem()
key_value = d.popitem()
print(key_value)  # Outputs ('age', 30)
print(d)          # Outputs {'name': 'Alice'}
# Remove with del
del d["name"]
print(d)  # Outputs {}

Impact of Mutability

Advantages of Mutability

  • Flexibility: Mutable dictionaries allow dynamic changes to the data, such as adding or removing keys while the program is running.
  • Efficiency: Changes are made in place, which is generally more efficient than creating new data structures.

Comparison with Immutable Structures

  • Lists: Lists are also mutable. You can add, remove, or modify elements in a list.
  • Sets: Sets are mutable collections but do not maintain order.
  • Tuples: Tuples are immutable. Once created, their elements cannot be changed.
  • Strings: Strings (str) are immutable. Any modification creates a new string.

Example of Comparison with Tuples: 

# Dictionary
d = {"a": 1, "b": 2}
d["c"] = 3
d["a"] = 10
del d["b"]
print(d)  # Outputs {'a': 10, 'c': 3}
# Tuple
t = (1, 2, 3)
# t[1] = 4  # This line would raise a TypeError because tuples are immutable

Using Immutable Dictionaries

If you need a dictionary where the elements cannot be changed, you can use collections.MappingProxyType, which provides a read-only view of a dictionary.

Example with MappingProxyType: 

from types import MappingProxyType
d = {
    "name": "Alice",
    "age": 30
}
# Create a read-only view
d_proxy = MappingProxyType(d)
print(d_proxy)  # Outputs {'name': 'Alice', 'age': 30}
# d_proxy["name"] = "Bob"  # This line would raise a TypeError because MappingProxyType is immutable

Summary

  • Mutability: Dictionaries in Python are mutable, allowing for changes such as adding, modifying, or deleting elements after their creation.
  • Advantages: The mutability of dictionaries provides flexibility and efficiency in managing data.
  • Comparison: Dictionaries are mutable like lists and sets, while tuples and strings are immutable.
  • Immutable Dictionaries: For scenarios where immutability is needed, MappingProxyType provides a read-only view of a dictionary.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *