Sobes.tech
Junior — Middle

What is the difference between mutable and immutable data types in Python and what are their main differences?

sobes.tech AI

Answer from AI

In Python, data types are divided into mutable and immutable depending on whether the object can be changed after its creation.

  • Immutable types: int, float, bool, str, tuple, frozenset

    • Once created, the content of the object cannot be changed.
    • Modifications create a new object.
  • Mutable types: list, dict, set, bytearray

    • The content of the object can be changed without creating a new object.

Main differences:

  • Behavior when assigning and copying: mutable objects can be changed in different parts of the program when passed by reference, which requires caution.

  • Use as dictionary keys: only immutable objects can be used as keys.

  • Performance: operations with immutable objects may create additional objects but ensure safety from unintentional modifications.

Example:

# Immutable type
s = "hello"
s2 = s.replace('h', 'j')  # creates a new object
print(s)  # hello
print(s2) # jello

# Mutable type
lst = [1, 2, 3]
lst.append(4)  # modifies the existing object
print(lst)  # [1, 2, 3, 4]