In Python, mutable data types are those whose values can be changed, while immutable data types are those whose values cannot be changed after they are created.
Mutable data types include lists, sets, and dictionaries, where their contents can be added, removed, or modified.
Immutable data types include integers, floats, strings, tuples, and frozensets, where their values cannot be modified once they are created.
Here are some examples of mutable and immutable data types in Python:
Mutable Example:
List: my_list = [1, 2, 3], my_list.append(4)
Dictionary: my_dict = {'a': 1, 'b': 2}, my_dict['c'] = 3
Set: my_set = {1, 2, 3}, my_set.add(4)
Immutable Example:
Integer: my_int = 5
Float: my_float = 3.14
String: my_string = "Hello, world!"
Tuple: my_tuple = (1, 2, 3)
| Property | Mutable Objects | Immutable Objects |
|---|---|---|
| Definition | Objects that can be modified after creation | Objects that cannot be modified after creation |
| Examples | Lists, dictionaries, sets | Numbers, strings, tuples |
| Memory Usage | consume more memory | memory efficient |
| Object | Can be modified after creation. | Cannot be modified after creation. |
| Identity | The identity of a mutable object remains same | identity is changed |
| Copying | changes to a copy can affect the original values | changes to a copy do not affect the original values |
Comments
Post a Comment