In Python, objects can be classified as mutable or immutable based on whether their state can be changed after they are created.
Mutable objects:
- Lists: Lists can be modified after they are created, allowing you to add, remove, or change elements. Example:
my_list = [1, 2, 3]
- Dictionaries: Dictionaries can have key-value pairs added, removed, or modified. Example:
my_dict = {'a': 1, 'b': 2}
- Sets: Sets can have elements added or removed. Example:
my_set = {1, 2, 3}
Immutable objects:
- Strings: Strings cannot be modified after they are created. Any operation that appears to modify a string actually creates a new string. Example:
my_string = 'Hello, world!'
- Tuples: Tuples are similar to lists but are immutable. Once created, you cannot add, remove, or change elements in a tuple. Example:
my_tuple = (1, 2, 3)
- Integers, floats, and booleans: These basic data types are also immutable. When you perform an operation on them, a new object is created. Example:
my_int = 42
The choice between mutable and immutable objects depends on the specific requirements of your program. Immutable objects provide safety and simplicity since their state remains constant throughout the program. On the other hand, mutable objects allow for greater flexibility and efficiency when changes to the data structure are needed.