Sobes.tech
Senior

What are immutable and mutable data types in Python?

sobes.tech AI

Answer from AI

In Python, data types are divided into mutable and immutable depending on whether their contents can be changed after the object is created.

Immutable types:

  • Primitive: int, float, bool
  • Strings (str)
  • Tuples (tuple)
  • frozenset

Objects of these types cannot be changed after creation. For example, if you change a string, a new object is created.

Mutable types:

  • Lists (list)
  • Sets (set)
  • Dictionaries (dict)

For these types, you can modify the contents without creating a new object.

Example:

s = "hello"
s2 = s.lower()  # a new string is created

lst = [1, 2, 3]
lst.append(4)  # the existing list is modified

Understanding mutability is important for memory management, passing arguments to functions, and preventing side effects.