Have you ever encountered unexpected results in your Python code when variables seemed to change in tandem? This article delves into the concepts of mutability and how changes in one variable can sometimes propagate to others. We’ll explain why this behavior occurs and how to manage it effectively.
Let’s explore this with a simple example:
1
2
3
numbers=[2,1,3,4,7]# points to the same objectnumbers2=numbers
numbers2
is not a distinct object; it’s a link to numbers
. Any changes to numbers will reflect in numbers2.
Here, changes in numbers
impact numbers2
because they both point to the same memory location and the same object.
Note: If you need to create a distinct object you need to use python copy module
However this works differently with immutable data types:
1
2
3
4
5
6
7
8
9
name="Walt"# second_name points to the same location as the namesecond_name=name# Here we create completely new object in memory second_name="Jesse"print(name)# Waltprint(second_name)# Jesse
This behaviour may cause unpredictable erorrs if you don’t know about it.
💡 Two Types of Changes in Python:
Mutation: Alters an object’s state. Example: modifying a list.
Change of Possession: Links to a completely different object.
1. Mutation:
Mutation involves altering an object’s state. This works for mutable data types like lists, sets, and dictionaries etc.
Note: You can understand that data type is mutable, if data type has “alter” methods. For example: dir(list) (append method); dir(set) (pop method).
Example 1 - Mutation in Lists:
1
2
3
4
5
6
7
8
# Mutable data type: Listnumbers=[1,2,3,4]# Mutation: Changing the list in-placenumbers.append(5)# Output: [1, 2, 3, 4, 5]print(numbers)
Example 2 - Mutation in Dictionaries:
1
2
3
4
5
6
7
8
# Mutable data type: Dictionaryperson={'name':'Alice','age':25}# Mutation: Modifying the dictionary in-placeperson['age']=26# Output: {'name': 'Alice', 'age': 26}print(person)
2. Change of Possession:
Change of possession involves linking to a completely different object. This is more common with immutable data types.
Example 1 - Change of Possession with Strings:
1
2
3
4
5
6
7
8
# Immutable data type: Stringgreeting="Hello"# Change of Possession: Creating a new stringgreeting=greeting+", World!"# Output: Hello, World!print(greeting)
Example 2 - Change of Possession with Tuples:
1
2
3
4
5
6
7
8
# Immutable data type: Tuplecoordinates=(3,4)# Change of Possession: Creating a new tuplecoordinates=(5,6)# Output: (5, 6)print(coordinates)
Python Operators: 🤔
is: Checks if two variables point to the same memory location. ==: Checks if two variables store the same data.
1
2
3
4
5
6
7
8
9
10
11
12
importcopynumbers=[1,2,3]# here we create a new object with # the same data as in numberscopy_of_numbers=copy.copy(numbers)# just a linklink_to_numbers=numbersnumbersiscopy_of_numbers# False they're two separate objnumbersislink_to_numbers# True they're same
🛠️ Mutability in Python:
Mutable: Lists, Sets, Dicts, Arrays, etc.
Immutable: Integers, Tuples, Strings, Booleans, Floats, Bytes, etc.