Junior — Middle
What are the differences between mutable and immutable data types?
sobes.tech AI
Answer from AI
In Python, data types are divided into mutable and immutable.
Mutable types allow changing the contents of an object after its creation. Examples: lists (list), sets (set), dictionaries (dict). For example, you can add an element to a list or change a value by key in a dictionary.
Immutable types cannot be changed after creation. Examples: numbers (int, float), strings (str), tuples (tuple). If you need to change a value, a new object is created.
The differences are important for understanding variable behavior, argument passing in functions, and memory optimization. For example, when passing a mutable object to a function, changes will be visible outside it, but with an immutable object — no.
Example:
lst = [1, 2, 3]
lst.append(4) # modifying the list
s = "hello"
s = s + " world" # a new string is created