what is mutable and immutable

what is mutable and immutable

1 year ago 42
Nature

In programming, objects can be classified as either mutable or immutable. Mutable objects can be changed after they are created, while immutable objects cannot be changed after they are created. Here are some key points to keep in mind:

Mutable Objects

  • Can be changed after they are created
  • Examples include lists, dictionaries, sets, and user-defined classes
  • Modifying a mutable object can be done in-place, without allocating a new object
  • Changes to a mutable object affect all references to that object

Immutable Objects

  • Cannot be changed after they are created
  • Examples include numbers (int, float, complex, and booleans), strings, tuples, frozen sets, and user-defined classes
  • Modifying an immutable object requires creating a new object with the desired changes
  • Immutable objects are often simpler to construct, test, and use, and are always thread-safe

When working with mutable and immutable data types, it is important to consider how using one or the other category of objects would impact your code. For example, working with immutable objects may require more memory because you cannot mutate the data directly in the object itself, and you need to create new objects instead, which may lead to many different but related copies of the same underlying data. On the other hand, working with mutable objects can be more efficient when you need to change the size or content of the object.

In Python, strings and tuples are immutable, while lists, dictionaries, and sets are mutable. In Java, everything (except for strings) is mutable by default, but you can make objects immutable by making all fields final and private.

Read Entire Article